• Selenium Video Tutorials

Selenium Webdriver - Explicit/Implicit Wait



Selenium Webdriver can be used in association with explicit, and implicit to achieve synchronization. The waits are mainly applied in the tests to deal with dynamic web pages.

Often there lies some lag time before the whole page loads, and web elements are completely available on the web page. The waits available in Selenium Webdriver help to hold back the test execution till an element appears/disappears on a web page in its correct state.

Let us discuss some of the wait types in Selenium Webdriver −

Implicit Wait

It is the default wait available in Selenium. It is a kind of global wait applicable to the whole driver session. The default wait time is 0, meaning if an element is not found, an error will be thrown straight away. However, if a wait time is set, an error will be thrown once the wait time surpasses. Once the element is identified, its reference is returned and execution moves to the next step. We should use implicit wait in an optimal way, a larger wait time would increase the execution time of the tests.

Syntax

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

In the above example, a NoSuchElementException will be thrown after 15 seconds.

Explicit Wait

It is similar to loops added to code that poll the web page for a particular scenario to become true prior exiting the loop and moving to the next line of code. If the situation is unfulfilled within the time set out, a timeout exception will be thrown.The explicit waits are applied to a specific element with its condition with the help of the ExpectedConditions and WebDriverWait classes. Some of the expected conditions for explicit waits are −

titleContains, alertIsPresent, invisibilityOfElementLocated(By locator), 
titleIs(), invisibilityOfElementWithText(By locator, String s), 
visibilityOf(), textToBePresentInElement(By locator, String s), 
visibilityOfElementLocated(By locator), visibilityOfAllElements(), 
presenceOfAllElementsLocatedBy(By locator), 
presenceOfElementLocated(By locator), 
elementToBeClickable(By locator), stalenessOf(WebElement e),  
textToBePresentInElementValue(), textToBePresentInElementLocated(), 
elementSelectionStateToBe(), elementToBeSelected(), 
frameToBeAvaliableAndSwitchToIt().

We should be cautious while adding both implicit and explicit waits in the same driver session, for instance having a combination of explicit wait of 15 seconds and implicit wait of 10 seconds can result in a timeout to occur after 20 seconds.

Syntax

WebDriverWait wt = new WebDriverWait(driver,5);
wt.until(ExpectedConditions.invisibilityOfElementLocated
   (By.xpath("//*[@class='mui−btn']")));

In the above example, a TimeOutException will be thrown after 5 seconds in case the expected condition of an element to be invisible is not met within that specified time.

Let us take an example, where we would try to identify the text Selenium - Automation Practice Form with the wrong xpath value and add an implicit wait. In such a scenario, once the timeout time is passed, we would get a NoSuchElementException.

The correct xpath for this element would be: /html/body/div/header/div[2]/h1. However, we would be using an incorrect xpath /html/body/div/header/div[2]/u1 in our implementation in order to get an exception.

Selenium Explicit Implicit 1

Example

Code Implementation on Implicitwts.java class file.

package org.example;

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class Implicitwts {
   public static void main(String[] args) throws InterruptedException {

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver();

      // adding implicit wait of 10 secs
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

      // launching a browser and open a URL
      driver.get("https://www.tutorialspoint.com/selenium/practice/selenium_automation_practice.php");

      // identify element with incorrect xpath value
      WebElement l = driver.findElement(By.xpath("/html/body/div/header/div[2]/u1"));
      l.click();

      // get text
      System.out.println("Get text : " + l.getText());

      // Quitting browser
      driver.quit();
   }
}

Output

Exception in thread "main" 
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: 
{"method":"xpath","selector":"/html/body/div/header/div[2]/u1"}
  (Session info: chrome=121.0.6167.160)
For documentation on this error, please visit: 
https://www.selenium.dev/documentation/webdriver/troubleshooting/errors#no-such-element-exception

Process finished with exit code 1

In the above example, we have received the NoSuchElementException since an incorrect xpath value is used to identify the element. Once the implicit wait time of 2 seconds passed, an exception was thrown.

Finally, the message Process finished with exit code 1 is received, signifying unsuccessful execution of the code.

Let us take another example, where we would see that a Timeout exception would be thrown while the explicit wait time had passed.

Example

Code Implementation on Explicitwt.java class file.

package org.example;

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;

public class Explicitwt {
   public static void main(String[] args) throws InterruptedException {

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver();

      // launching a browser and open a URL
      driver.get("https://www.tutorialspoint.com/index.htm");

      // identify element with locator xpath
      WebElement l = driver.findElement
         (By.xpath("/html/body/header/nav/ul/li[2]/a"));

      // explicit wait 2 secs for presence of incorrect element
      WebDriverWait wt = new WebDriverWait(driver, Duration.ofSeconds(2));
      wt.until(ExpectedConditions.presenceOfElementLocated
         (By.xpath("/html/body/header/nav/ul/li[2]/li")));

      // get text after presence of element condition is met
      System.out.println("Get text : " + l.getText());

      // Quitting browser
      driver.quit();
   }
}

Output

Exception in thread "main" org.openqa.selenium.TimeoutException: 
   Expected condition failed: waiting for presence of element located by: 
   By.xpath: /html/body/header/nav/ul/li[2]/li (tried for 2 second(s) 
   with 500 milliseconds interval)
   at org.openqa.selenium.support.ui.WebDriverWait.
      timeoutException(WebDriverWait.java:84)
   at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:230)
   at org.example.Explicitwt.main(Explicitwt.java:25)
Caused by: org.openqa.selenium.NoSuchElementException: no such element: 
   Unable to locate element: 
{"method":"xpath","selector":"/html/body/header/nav/ul/li[2]/li"}
  (Session info: chrome=121.0.6167.85)

In the above example, we have received the TimeOutException since an expected condition for presence of an element was not met within an explicit wait of 2 seconds. Once the explicit wait time of 2 seconds passed, an exception was thrown.

Finally, the message Process finished with exit code 1 was received, signifying unsuccessful execution of the code.

In this tutorial, we had discussed how to handle implicit and explicit waits using Selenium Webdriver.

Advertisements