How to Use WebDriverWait in Selenium Java: A Step-by-Step Tutorial

KSHITIJ SHARMA
13 min readJun 26, 2023

How to Use WebDriverWait in Selenium Java: A Step-by-Step Tutorial

What is Selenium Webdriver

Selenium WebDriver is a powerful tool for automating web applications, but timing issues can often lead to flaky tests. To overcome these challenges, understanding and effectively utilising wait commands is crucial. In this article, we will explore various wait examples using a practical website, “Google.com.” We will cover implicit, explicit and fluent waits, along with code snippets, to demonstrate their implementation in real-world scenarios. By the end of this article, you will have a solid understanding of wait commands in Selenium WebDriver and be able to write robust and reliable automation scripts.

Introduction

Within Selenium WebDriver, wait commands are essential in addressing timing issues and in synchronising test automation to the behaviour of web-based applications. Problems with timing are usually due to issues like delay in network connections and dynamic loading of pages and synchronous operations. These problems can result in failure of tests in which elements aren’t yet accessible or unsolvable when automated scripts try to access them.

Wait commands offer an effective solution by enabling automation scripts to pause execution until certain conditions have been met. By including appropriate waits in our tests, we can ensure they wait for elements such as appearing or becoming clickable before taking further actions — and ensuring our scripts interact with the website at exactly the right moment, providing more reliable and stable interactions overall.

Effectively using wait commands is a crucial element of a successful test automation. Through managing timing issues with a sense of flexibility, it is possible to improve precision and consistency in our tests, resulting in passing of our test cases and test suites.

Selenium WebDriver provides three commands to use waits in tests.

  1. Implicit Wait
  2. Explicit Wait
  3. Fluent Wait

Implicit Waits -

Implicit waits in Selenium WebDriver allow you to set a global wait time that applies to all subsequent WebDriver commands, so if the WebDriver cannot locate elements immediately it will wait a set period before throwing NoSuchElementException.

Setting Implicit Wait

To set an implicit wait, call the WebDriver instance manage() method, followed by timeouts() and implicitlyWait() methods, with implicitlyWait() called as needed (an example being 10 seconds of waiting is here:). Here is how an implicit wait can be set:

WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

In the above example, we created a new instance of ChromeDriver setting the implicit wait time to 10 seconds by using an implicitlyWait() method. This means that if WebDriver cannot find an element immediately, it will wait for up to 10 seconds for the element to appear before throwing a NoSuchElementException.

Implicit waits can be especially helpful in cases in which elements on a web page take some time to load or become intractable due to network latency, AJAX requests or dynamic content. By setting an appropriate implicit wait value in your automation scripts, you can ensure they wait until all elements become accessible before engaging them, thus increasing reliability and stability of tests.

Consciously deploying implicit waits is the key to test efficiency; setting too long implicit wait times may slow test execution down while too short waits may cause failure in tests if elements take more than anticipated to load. Therefore, it’s recommended examining how your application under test behaves before setting an implicit wait time that best matches its behavior and adjust accordingly.

Implicit waits can provide basic level synchronisation; for more precise and granular control over waiting conditions, explicit waits using WebDriverWait class are usually preferred. We will explore explicit waits more in depth in subsequent sections.

Let’s consider a practical scenario where we want to wait for an element to be visible on the google.com website before interacting with it.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class ImplicitWaitExample {
public static void main(String[] args) {
// Set the path to the ChromeDriver executable
System.setProperty(“webdriver.chrome.driver”, “path/to/chromedriver”);
// Create a new instance of the ChromeDriver
WebDriver driver = new ChromeDriver();
// Set the implicit wait time
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// Navigate to the website
driver.get(“https://google.com”);
// Find the element with the given ID
WebElement element = driver.findElement(By.id(“elementId”));
// Perform actions on the element
element.click();
// Close the browser
driver.quit();
}
}

In the example above, we first set the path to the ChromeDriver executable using System.setProperty(). After that, we create a copy of ChromeDriver.

Next, we set the implicit wait time to 10 seconds using driver.manage().timeouts().implicitlyWait(). This means that if WebDriver cannot find an element immediately, it will wait for up to 10 seconds for the element to be available on the web page before throwing a NoSuchElementException.

We navigate to the desired website using driver.get(), and then find the element on the page with the specified ID using driver.findElement(). If the element isn’t immediately visible, WebDriver will wait for approximately 10 seconds before it shows up.

Once we have found the element after which we can take actions with it, like clicking it with element.click().

Then closing the browser by calling driver.quit() to close our WebDriver session.

Explicit Wait

The explicit waits available in Selenium WebDriver offer more precise control of waiting for specific conditions to be fulfilled prior to starting testing. In contrast to implicit wait, explicit wait is applied to individual elements or conditions, which allows you to create specific wait strategies to suit different scenarios.

Setting Explicit Wait

To enable explicit wait in Selenium WebDriver, you need to create a WebDriverWait instance and set the maximum wait duration (timeout) as well as the interval for polling. The WebDriverWait class has a variety of expected conditions that can be used to wait for certain conditions to be fulfilled prior to beginning the test.

WebDriverWait Class

The WebDriverWait class in Selenium WebDriver enables explicit waits by providing methods to wait for specific conditions to be satisfied before proceeding further. It is part of the org.openqa.selenium.support.ui package.

Expected conditions are methods available in the ExpectedConditions class and can be used in combination with WebDriverWait to define custom wait strategies. Here are all the webdriver wait expected conditions:

alertIsPresent(): Waits until an alert is present.
elementToBeClickable(By locator): 
Waits until the element identified by the specified locator is clickable.
elementToBeSelected(WebElement element): 
Waits until the specified element is selected.
frameToBeAvailableAndSwitchToIt(By locator): 
Waits until the frame identified by the specified locator is available
and switches the driver’s focus to that frame.
invisibilityOf(WebElement element): 
Waits until the specified element is invisible.
invisibilityOfAllElements(List<WebElement> elements): 
Waits until all of the specified elements are invisible.
presenceOfAllElementsLocatedBy(By locator): 
Waits until all elements matching the specified locator
are present in the DOM.
presenceOfElementLocated(By locator): 
Waits until at least one element matching the specified locator
is present in the DOM.
textToBePresentInElement(WebElement element, String text): 
Waits until the specified element contains the given text.
textToBePresentInElementLocated(By locator, String text): 
Waits until the element identified by the specified locator
contains the given text.
titleContains(String title): Waits until the title of the page 
contains the specified text.
titleIs(String title): 
Waits until the title of the page matches the specified title.
visibilityOf(WebElement element): 
Waits until the specified element is visible.
visibilityOfAllElements(List<WebElement> elements): 
Waits until all of the specified elements are visible.
visibilityOfAllElementsLocatedBy(By locator): 
Waits until all elements matching the specified locator are visible.
visibilityOfElementLocated(By locator): 
Waits until the element identified by the specified locator is visible.

For WebDriverWait to work you must create an instance and then specify the maximum waiting duration (timeout duration) as well as the frequency of monitoring to see if the conditions are met (polling time).The until() method of WebDriverWait is then used to wait until the condition is met.

Here’s an example of using WebDriverWait to wait for an element to be clickable:

WebDriver driver = new ChromeDriver();
WebDriverWait wait = new WebDriverWait(driver, 10); // Timeout set to 10 seconds
driver.get(“https://www.lanbdatest.com");
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id(“elementId”)));
element.click();

In the example above, we create a new instance of WebDriverWait, specifying the WebDriver instance (driver) and the maximum wait time of 10 seconds. We navigate to the desired webpage using driver.get().

The until() method is then used with the ExpectedConditions class to wait until the element with the specified ID becomes clickable. Once the condition is satisfied, the element is returned, and we can perform actions on it, such as clicking on it.

Let’s consider a practical scenario where we want to wait for an element to be visible on the google.com website before interacting with it.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
public class ExplicitWaitExample {
public static void main(String[] args) {
// Set the path to the ChromeDriver executable
System.setProperty(“webdriver.chrome.driver”, “path/to/chromedriver”);
// Create a new instance of the ChromeDriver
WebDriver driver = new ChromeDriver();
// Navigate to the website
driver.get(“https://www.google.com”);
// Set the explicit wait timeout to 10 seconds
WebDriverWait wait = new WebDriverWait(driver, 10);
// Wait for the element to be visible
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(“elementId”)));
// Perform actions on the element
element.click();
// Close the browser
driver.quit();
}
}

In the example above, we start by setting the path to the ChromeDriver executable using System.setProperty(). Then, we create a new instance of the ChromeDriver.

We navigate to the desired website using driver.get().

Next, we create an instance of WebDriverWait, specifying the WebDriver instance (driver) and the maximum wait time (timeout) of 10 seconds. This means that WebDriver will wait for up to 10 seconds for the expected condition to be met.

We use ExpectedConditions.visibilityOfElementLocated() as the expected condition. This condition waits for an element with the specified ID to become visible on the web page.

The until() method of WebDriverWait is used to wait until the expected condition is met. It returns the located element once it becomes visible.

Once the element is found, we can perform actions on it, such as clicking on it using element.click().

Finally, we close the browser using driver.quit() to end the WebDriver session.

By utilizing explicit wait, we ensure that WebDriver waits for a specific condition to be met before proceeding with the test execution. This lets us handle the dynamic nature of elements and asynchronous behavior and other issues with timing that result in a more reliable and stable testing automation.

Fluent Wait

FluentWait is one of the classes within Selenium WebDriver that provides more sophisticated options to define customized wait strategies. It lets you set the maximum time for waiting (timeout) and the interval of polling and set rules to be ignored during the waiting.

With FluentWait it is possible to define an adaptable and customisable wait mechanism that can handle the dynamic nature of elements and asynchronous behaviors, or any other issues with timing that could arise in test automation.

Setting Fluent Wait

Let’s consider a practical scenario where we want to wait for an element to be visible on the google.com website before interacting with it.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Wait;
import java.time.Duration;
import java.util.NoSuchElementException;
public class FluentWaitExample {
public static void main(String[] args) {
// Set the path to the ChromeDriver executable
System.setProperty(“webdriver.chrome.driver”, “path/to/chromedriver”);
// Create a new instance of the ChromeDriver
WebDriver driver = new ChromeDriver();
// Navigate to the website
driver.get(“https://www.google.com”);
// Set up FluentWait with a timeout of 10 seconds and a polling interval of 500 milliseconds
Wait<WebDriver> wait = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(10))
.pollingEvery(Duration.ofMillis(500))
.ignoring(NoSuchElementException.class);
// Use FluentWait to wait for the element to be visible
WebElement element = wait.until(driver -> driver.findElement(By.id(“elementId”)));
// Perform actions on the element
element.click();
// Close the browser
driver.quit();
}
}

In the example above, we first set the path to the ChromeDriver executable using System.setProperty(). Then, we create a new instance of the ChromeDriver.

We navigate to the desired website using driver.get().

Next, we create an instance of FluentWait, specifying the WebDriver instance (driver) as the input. We set the maximum wait time to 10 seconds using withTimeout(), the polling interval to 500 milliseconds using pollingEvery(), and instruct FluentWait to ignore NoSuchElementException using ignoring().

Inside the until() method, we provide a lambda expression (driver -> driver.findElement(By.id(“elementId”))) that defines the condition to wait for. In this example, it waits until the element with the specified ID becomes visible on the web page.

Once the condition is met, the until() method returns the located element.

Finally, we can perform actions on the element, such as clicking on it using element.click().

Utilizing FluentWait it gives us the ability to design custom wait strategies that include specific timeout intervals and polling intervals as well as the exceptions we can ignore. This allows us to manage various synchronization scenarios efficiently during testing automation.

Timeouts and Exceptions

Within Selenium WebDriver, a TimeoutException is thrown when a defined wait time is exceeded as well as the expected condition isn’t satisfied. This is typically the case when the condition expected to occur doesn’t occur within the specified timeout period.

To deal with the TimeoutException effectively within your automated test scripts, you can employ try-catch blocks to detect the error and then handle it in the right way.

Handling timeouts and exceptions

Here’s an example of how to handle a TimeoutException in Java with Selenium WebDriver:

import org.openqa.selenium.By;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class TimeoutExceptionExample {
public static void main(String[] args) {
// Set the path to the ChromeDriver executable
System.setProperty(“webdriver.chrome.driver”, “path/to/chromedriver”); // Create a new instance of the ChromeDriver
WebDriver driver = new ChromeDriver();
try {
// Create a WebDriverWait instance with a timeout of 10 seconds
WebDriverWait wait = new WebDriverWait(driver, 10);
// Navigate to the website
driver.get(“https://www.google.com”);
// Wait for the element to be visible
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(“elementId”)));
// Perform actions on the element
element.click();
} catch (TimeoutException e) {
// Handle the TimeoutException
System.out.println(“Timeout occurred. Element not found within the specified time.”);
e.printStackTrace();
} finally {
// Close the browser
driver.quit();
}
}
}

In the example above, we first set the path to the ChromeDriver executable using System.setProperty(). Then, we create a new instance of the ChromeDriver.

Inside the try block, we create a WebDriverWait instance with a timeout of 10 seconds. We navigate to the desired website using driver.get().

We use wait.until() with ExpectedConditions.visibilityOfElementLocated() to wait for the element with the specified ID to become visible. If the element is not found within the timeout duration, a TimeoutException will be thrown.

To handle the TimeoutException, we catch it using a catch block specifically for TimeoutException. Inside the catch block, we can perform custom actions, such as printing an error message or logging the exception.

In the finally block, we close the browser using driver.quit() to ensure that the WebDriver session is properly terminated.

In handling the TimeoutException we can effectively deal with situations where the desired conditions are not met within the specified timeout duration. This allows us to send clear error messages, or take the appropriate action to deal with the scenario during automation of tests.

Best Practices for Wait Command Usage

Combining Implicit and Explicit Waits

When using waits in Selenium WebDriver, it’s essential to take a calculated approach to maximize your wait strategies depending on the different scenarios you’ll encounter when automating. Combining explicit and implicit waits will help improve timing and enhance the efficiency of test results

Here are a few best methods to use a combination of explicit and implicit waits:

  • Set a Reasonable Implicit Wait Time: Configure a reasonable implicit wait time using driver.manage().timeouts().implicitlyWait() to provide a global wait time for elements to be available. This helps handle basic synchronization issues and avoids unnecessary delays. However, avoid setting excessively long implicit wait times as they can slow down test execution.
  • Use Explicit Waits for Precise Conditions: Utilize explicit waits with WebDriverWait and ExpectedConditions to wait for specific conditions that require more precise synchronization. Explicit waits provide granular control over waiting conditions, allowing you to wait for elements to be clickable, visible, or present based on the requirements of your tests.
  • Leverage FluentWait for Customization: When you need more advanced control over wait strategies, FluentWait offers additional customization options such as specifying the timeout duration, polling interval, and exceptions to ignore. FluentWait can handle dynamic elements, AJAX requests, and other timing issues more effectively.
  • Analyze Application Behavior: Analyze the behavior of the application under test to identify areas where explicit waits are necessary. Determine the specific conditions that need to be met before interacting with elements and use explicit waits accordingly.
  • Use Specific Expected Conditions: Choose the appropriate expected conditions provided by ExpectedConditions class, such as elementToBeClickable(), visibilityOfElementLocated(), or presenceOfElementLocated(), based on the behavior of elements and your test requirements. This helps ensure that your tests wait only as long as needed.
  • Balance Wait Times: Strike a balance between wait times and test efficiency. Setting excessively long wait times can slow down test execution unnecessarily, while setting very short wait times may lead to flaky tests if elements take longer to load. Adjust the wait times based on the stability and behavior of the application.
  • Handle Timeouts Gracefully: Wrap your wait commands with try-catch blocks to handle TimeoutExceptions and other exceptions that may occur during waits. This allows you to handle timeout scenarios gracefully and perform appropriate actions, such as logging errors or capturing screenshots.

By combining implicit and explicit waits judiciously, you can optimize your wait strategies based on different scenarios encountered during automation. This helps improve synchronization, enhance test reliability, and ensure efficient execution of your test scripts.

Conclusion

This article discussed the significance of wait commands within Selenium WebDriver and their role in the creation of stable and reliable tests automation scripts. We examined various types of waits, such as explicit and implicit waits and The FluentWait Class. We also talked about the best practices for the use of wait commands and discussed how to handle timeouts and other exceptions in a graceful manner.

Wait commands play a crucial role in overcoming timing issues during test automation. They allow us to synchronize our tests with the dynamic behavior of web applications, ensuring that our automation scripts interact with elements at the appropriate time. By using waits effectively, we can enhance the stability and reliability of our tests.

Key Takeaways:

  • Wait commands are essential for handling synchronization issues during test automation.
  • Implicit waits provide a global wait time for elements to be available.
  • Explicit waits offer more precise synchronization by waiting for specific conditions to be met.
  • FluentWait provides advanced customization options for wait strategies.
  • Customizing the timeout duration and polling interval can optimize wait behavior.
  • Combining implicit and explicit waits can enhance synchronization and test efficiency.
  • ExpectedConditions class offers various methods to wait for common scenarios.
  • Gracefully handling timeouts and exceptions ensures robust test execution.

Following the most effective practices and utilizing wait commands correctly to create robust and solid test automation programs that adjust to the dynamic nature of web-based applications. Make sure you analyze your application’s behavior, select the right waiting strategies and balance waiting times to ensure optimal execution of tests. Have fun testing!

--

--