Selenium Waiting for Element

Since Selenium simulate the actual behavior of the browser, then the page loading time will now adds to the restrictions of the test or automation. Sometimes, we need to wait for a certain element to be clickable, or to appear before we perform other behaviors. In that case, in Selenium waiting for element makes it easy with the use of WebDriverWait class.
 
If you are new to selenium, you may want to visit first the article on how to start automating web application using Selenium:
Selenium Java Tutorial

Selenium Waiting for Element

WebDriverWait class contains a method until which accept a ExpectedConditions class argument that will specify the condition on which the code will continue to run or execute. For example, we have a page where there is link text Candidates that will show.

WebElement linkElement = new WebDriverWait(webDriver, 10).until(ExpectedConditions.presenceOfElementLocated(By.linkText("Candidates")));

where 10 is the time in seconds where the webDriver will wait before it throws a time out exception. The example above will wait for an element, probably an a tag with link text “Candidates” that has a default wait time of 10 seconds for the element to be present before it throws an exception.

Selenium Waiting for Page to Load

We can also wait for all the scripts to load before we perform any actions. We can do this using similar code below:

new WebDriverWait(webDriver, 10).until(
                d -> ((JavascriptExecutor) d).executeScript("return document.readyState").equals("complete"));

This uses Java 8 Lambda expression. The example above will wait for the document.readyState to be ready before it continues executing the codes.


The class ExpectedConditions contains different static methods that you can use to satisfy your condition. Some methods are:

ExpectedConditions.elementToBeClickable
ExpectedConditions.visibilityOf
ExpectedConditions.presenceOfElementLocated

and so on. Please refer to this page for the documentation of ExpectedConditions class.

Share this tutorial!