Passionate to Quality

How To Use Wait in Selenium Webdriver

Selenium_Wait

Sometime it happens that you are doing automation scripting using selenium webdriver , your web element takes time to load or it loads based on some parent condition so at that time you have to tell selenium to wait till element loads. In this situation selenium offers different wait commands.

  • Implicit Wait : This helps to tell selenium web driver that do not fire directly exception if element not found. Wait till specified time to find element. This is very simple and straight wait command.

Code Example :

WebDriver driver = new FirefoxDriver();

driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

driver.get(“http://thesoftwaretesting.com/”);

WebElement myElement = driver.findElement(By.id(“ElementId”));

So as per above code it is telling to selenium that wait for 20 seconds to find element before fire exception.

  • Explicit Wait : Explicit wait helps to wait until certain condition occurs.  It allow to specify expected conditions for wait.

Code Example :

WebDriver driver = new FirefoxDriver();

driver.get("http://thesoftwaretesting.com/");

WebElement myElement = (new WebDriverWait(driver, 30))
.until(ExpectedConditions.presenceOfElementLocated(By.id("ElementId")));

  • Fluent Wait : Fluent wait uses 2 parameters , Timeout value and polling frequency.Each FluentWait object defines the maximum amount of time to wait for a specific condition and frequency with which to check the condition.

Code Example :

Wait wait = new FluentWait(driver)
.withTimeout(30, SECONDS)
.pollingEvery(2, SECONDS)
.ignoring(NoSuchElementException.class);

WebElement testElement = wait.until(new Function() {

public WebElement addwait(WebDriver driver) {

return driver.findElement(By.id("ElementId"));

}
});

So as per above code webdriver will check for element for every 2 seconds until timeout value 30 seconds. Also It will ignore specified exception.

Wait commands are best option and standard way to wait for element rather than Thread.sleep(); .

Email Us for any query




Email: inquiry@thesoftwaretesting.com

DISCLAIMER

Thesoftwaretesting.com provides QA services world wide. We Specialized in Manual Testing, Automation Testing, Web Testing and Mobile App. Testing. We focus on providing top notch Quality assurance services.