This post was most recently updated on June 14th, 2019
There are three types of waits in selenium. Implicit wait, explicit wait and fluent wait.
Implicit wait:
Once you define implicit wait then it will wait for all findElement() and findElements(). Webdriver tries to find element in DOM after every polling time, if element is not found then it wait for polling time(0.5 Seconds) and again try to find the element until maximum time defined is over. If element is not found then it will throw NoSuchElementException.
Polling time can be changed using
1 |
<span style="font-size: 16px;">wait.pollingEvery(1, TimeUnit.SECONDS);</span> |
Usage:
1 2 |
<span style="font-size: 16px;">WebDriver driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);</span> |
In above code it will wait for maximum 10 seconds if element is not found within 10 seconds then it will throw exception.
Explicit wait:
Explicit wait would be defined to particular web element. It will wait for single web element. For example if one of the web element takes more time than implicit wait then instead of changing implicit wait time it is better to define explicit wait.
Usage:
1 2 3 |
<span style="font-size: 16px;">WebDriver driver = new ChromeDriver(); WebDriverWait wait = new WebDriverWait(driver, 20); WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id(“username”)));</span> |
Fluent wait:
Fluent wait is similar to explicit wait the difference is in fluent wait we can define polling time. And we can ignore the exception.
Usage:
1 2 3 4 5 6 7 8 9 10 11 |
<span style="font-size: 16px;">Wait<WebDriver> wait = new FluentWait<WebDriver>(driver) .withTimeout(50, SECONDS) .pollingEvery(10, SECONDS) .ignoring(NoSuchElementException.class); WebElement Element = wait.until(new Function<WebDriver, WebElement>() { public WebElement apply(WebDriver driver) { return driver.findElement(By.xpath("//button[text()='Login']")); } });</span> |