Monday, May 23, 2016

WebDriver Explicit Wait: wait for element to load

If you want webdriver to wait for any element to be visible, we can use explicit wait. In simple way iof we use wait function for any given time, we can not make sure how muych time it will take to an element to get visible. Or if you give more time for wait, may be element gets visible early and un necessary your sript wait for the given time. So to manage this, we can use wait in diff way by creating instance variable of WebDriverWait class. This can be as below:

import org.openqa.selenium.By;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Test1 {

       public static void main(String[] args)
       {
             
              FirefoxDriver driver = new FirefoxDriver();
              driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); //This is implicit wait used

              driver.get("http://vishalsachan.blogspot.in");
        WebDriverWait wait = new WebDriverWait(driver, 30);
        wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.id("as_rst")));
        driver.findElement(By.id("as_rst")).click();
       }
}


In example above, script will wait only in that step  for 30 seconds or until element visible (whatever occurs first) and will move next step.

No comments :

Post a Comment