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
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.
We can also wait for all the scripts to load before we perform any actions. We can do this using similar code below:
This uses Java 8 Lambda expression. The example above will wait for the document.readyState to be ready before it continues executing the codes.
ExpectedConditions.elementToBeClickable ExpectedConditions.visibilityOf ExpectedConditions.presenceOfElementLocated
and so on. Please refer to this page for the documentation of ExpectedConditions class.