August 10, 2015

How to Use Explicit Wait in Selenium Webdriver

Here is another post which will explains you about Explicit wait.

Below is the definition of explicit wait from selenium docs:

An explicit waits is code you define to wait for a certain condition to occur before proceeding further in the code. The worst case of this is Thread.sleep(), which sets the condition to an exact time period to wait. There are some convenience methods provided that help you write code that will wait only as long as required. WebDriverWait in combination with ExpectedCondition is one way this can be accomplished.

In simple words...you can use explicit wait where Implicitwait doesnt work. Ex: For Ajax elements, dynamically loading elements Implicit wait will not work. To handle Ajax and Dynamically loading elements we have to use Explicit wait.


In Below example

After clicking Start button it will take some time get text "Hello World"

we have to wait until that text present / wait until the element loads.


Here is explicit wait example...






Explicit wait has so many options...

Below are some of the options in ExpectedConditions...



Here is the Code:






package sample;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class Explicitwait_Test {
 public WebDriver driver;
 public WebDriverWait wait;

 @Test
 public void testExplicitwait_Test() throws Exception {

  driver.get("http://the-internet.herokuapp.com");
  driver.findElement(By.linkText("Dynamic Loading")).click();
  driver.findElement(By.linkText("Example 1: Element on page that is hidden")).click();
  driver.findElement(By.xpath("//div[@id='start']/button")).click();
//  Explicit wait --wait until element visible
  wait = new WebDriverWait(driver, 10);
  wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@id='finish']/h4")));
  String msg=driver.findElement(By.xpath("//div[@id='finish']/h4")).getText();
  System.out.println("Message is : "+msg);
  
 }

 @BeforeClass
 public void beforeClass() {
  driver = new FirefoxDriver();
  driver.manage().window().maximize();
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
 }

 @AfterClass
 public void afterClass() throws Exception {
  driver.quit();
 }

}

2 comments: