Tuesday, 11 November 2014

Wait commands in Selenium Webdriver

While executing our scripts for websites, some times wait command is needed. Like, sometimes we need to wait for an element to load, then only we can perform task on the same.
Selenium webdriver provides 2 types of wait commands: Implicit Wait & Explicit Wait. And it is always good to prefer implicit wait over explicit wait.

Implicit Wait:
Here in implicit wait, we need to write some wait command and set some time, so that it will wait for that amount of time for that element to load. And as it is implicit wait, it will be applicable to all elements in webdriver.

Sometimes, if we don't use use any wait command, then our webdriver script may get failed. It is because, the element on which we are about to perform action is not found by the webdriver locators as that element takes some time to load on the web page.

Here is the Implicit wait command below.
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

In this command, webdriver will wait for 20 seconds for every element, if that element doesn't appear on webpage.

Let see an example here.
public static void main(String[] args){
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.findElement(By.id("Email")).sendKeys("testuser1@gmail.com");
driver.findElement(By.id("Passwd")).sendKeys("xyz");
}

Here in the above code, we have set implicit time as 20 seconds. And we have two elements here: Email & Password. So, here webdriver will wait for 20 seconds, if the element is not found. After 20 seconds, if it is found, it will proceed else will throw error.


Explicit Wait:
As we discussed earlier, Implicit wait will be applicable to all web elements present. But Explicit will be applicable for the element we choose.
Here the command will look like below.

WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.elementToBeClickable(By.id("Email")));

Lets see an example here.

public static void main(String[] args){
WebDriver driver = new FirefoxDriver();
driver.findElement(By.id("Email")).sendKeys("testuser1@gmail.com"); 
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.elementToBeClickable(By.id("Passwd")));
driver.findElement(By.id("Passwd")).sendKeys("xyz");
}

Here, for Email field, there is no wait implemented. But for Password field, webdriver will wait for 20 seconds until that element is clickable. And once element is found clickable, then it will enter the password.

Instead of "elementToBeClickable", we can use "presenceOfElementLocated" as well.
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("passwd")));
Here, it will wait until the password field is located. Then it will perform the next action on that web element.

1 comment :