Every browser application has it’s own delay in loading the elements when we open a web application / navigate from one page to another / perform some action.
Loading depends on different criteria like internet bandwidth, technology used in the application, server capacity, no of users accessing the browser app etc…
While executing tests in different machines/environments, we need to make sure our script or code should wait till the elements load/present on the web page to perform some action upon them…
Selenium provides different ways to wait for an element on web page…
let’s see them one by one –
Hard waits
Thread.sleep(2000);
Implicit wait
WebDriver driver = new FirefoxDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.get("http://www.qavalidation.com");
The above code will wait for 10 sec only to find any elements on the web page, and this time is fixed to wait for an element through out the code (until unless we rewrite the statement with different wait time).
As soon as found the element with in that time bound, performs action as coded,
else (if the time is over but not found), WebDriver throws exception (not able to locate the element)
This above code will wait for an element to locate only, but there are situations where we wish to wait for specific webelement property conditions like enabled, to be clickable, presence etc…, for this we can use explicit wait.
Explicit wait
By WebElement locator
WebDriverWait wait = new WebDriverWait(driver, 30); wait.until(ExpectedConditions.elementToBeClickable(By.id("Inbox")));
if before 30sec it will find the element to be clickable, then instead wait for 30sec to complete control goes to next code line.
same we have conditions like, elementtobevisible, presenceofanelement…if we enter a dot after ExpectedConditions, will get one by one element property to wait.
Fluent wait
There are situations where we want to wait for an element for specific time with our own polling time (how frequently) so selenium will locate an element.
public class Fluentw8 { static WebDriver driver; public static void main(String[] args) { driver = new FirefoxDriver(); driver.get("http://qavalidation.com/"); String desc = getElement(By.className("site-description")).getText(); System.out.println(desc); } public static WebElement getElement(final By locator) { FluentWait<WebDriver> wait = new FluentWait<WebDriver>(driver) .withTimeout(30, TimeUnit.SECONDS) .pollingEvery(5, TimeUnit.SECONDS) .ignoring(NoSuchElementException.class); WebElement element = wait.until(new Function<WebDriver, WebElement>() { @Override public WebElement apply(WebDriver arg0) { return arg0.findElement(locator); } }); return element; } }
1 Comment