Selenium WebDriverWait: Implementing The Explicit Wait Command

Upendra Prasad Mahto

Posted On: July 28, 2023

view count40799 Views

Read time18 Min Read

In the dynamic realm of automation testing, achieving flawless execution and dependable results is of utmost importance. As web applications grow more intricate and user-centric, conventional test scripts may struggle to handle asynchronous behavior and varying loading times. This is where Selenium WebDriverWait emerges as a game-changer.

WebDriverWait, a potent feature of Selenium, the industry-standard web application testing tool, empowers testers to apply intelligent delays or “waits” in their scripts. These waits ensure that interactions with web elements occur precisely when they are ready, rather than being forced prematurely. In this blog, we will delve into the significance of Wait commands in automation testing and explore how Selenium’s WebDriverWait elevates the efficiency and accuracy of test suites. By addressing the challenges posed by asynchronous web applications, network latencies, cross-browser inconsistencies, and UI rendering, WebDriverWait not only enhances test stability and reliability but also improves overall test performance.

In this blog, we will briefly look at the concept of the Explicit Wait command in Selenium. Subsequently, we will look at Selenium WebDriverWait, a Java class that implements the Explicit Wait command.

We will discuss the benefits of Selenium WebDriverWait in automation testing. We’ll also explore ExpectedConditions in Selenium, covering its types and commonly used expected conditions. We’ll provide an illustrative example to demonstrate the implementation of Selenium WebDriverWait. This comprehensive approach will equip you with a strong foundation in working with one of the Wait Commands in Selenium.

If you’re looking to improve your Selenium interview skills, check out our curated list of Selenium interview questions and answers.

What is Selenim WebDriverWait?

Selenium WebDriver offers different types of Wait Commands to handle synchronization in test automation. The concept of Selenium Wait revolves around pausing the execution of the script until certain conditions are met, ensuring that the test proceeds only when the desired state or element is available.

There are three types of Wait Commands:

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

types of Wait Commands

“WebDriverWait” is a class in Java provided by the Selenium framework that allows you to implement the concept of Explicit Waits in your test automation scripts. It allows you to define custom wait conditions and specify the maximum duration for the WebDriver to wait until the condition is satisfied. It provides control and flexibility compared to Implicit Waits, which are based on a fixed waiting time.

Selenium WebDriverWait class allows defining expected conditions using built-in methods provided by the ExpectedConditions class, such as element visibility, element clickability, text presence, and many more.

You may check out our blog on Selenium Wait to learn in-depth about the Selenium Wait commands.

Benefits of Using WebDriverWait

The implementation of the Explicit Wait command using the Selenium WebDriverWait class offers various benefits as listed below:

  • Selenium WebDriverWait allows your test scripts to wait for specific conditions to be met before proceeding, ensuring that the elements are ready for interaction. This reduces the chances of encountering errors or failures due to time-related issues.
  • Selenium WebDriverWait is particularly useful for handling dynamic web pages where elements may appear or change asynchronously. It enables you to wait for elements to be visible, clickable, or present before interacting with them, accommodating the dynamic nature of web applications.
  • Selenium WebDriverWait offers the flexibility to define custom wait conditions tailored to your specific testing requirements. You can create conditions based on JavaScript, CSS, or other relevant techniques, allowing you to handle unique scenarios not covered by built-in expected conditions.

Getting Started with Explicit Wait using Selenium WebDriverWait Class in Java

The Explicit Wait is a more intelligent approach than the Implicit Wait to handle synchronization in automation testing. Unlike Implicit, Explicit Wait allows you to pause the program execution for specific elements until they meet the desired conditions. It also provides more control and flexibility and is especially useful for waiting on dynamically loaded Ajax elements.

To use Explicit Wait, you must utilize the ExpectedConditions provided by Selenium.

Let’s discuss the ExpectedConditions in Selenium Webdriver.

ExpectedCondition in Selenium Webdriver

In automation testing, ensuring that the rendering of the web page and your instructions are in sync before proceeding is essential. Therefore, Selenium WebDriver provided ExpectedConditions that are used for performing Explicit Waits on a certain condition. These conditions are accessible in various programming languages and provide a user-friendly approach to waiting for specific conditions to be fulfilled. The availability of these conditions may differ based on the Selenium language bindings used.

Types of ExpectedConditions in Selenium Java

There are generally four categories of Expected Conditions in Selenium Java,

  1. ExpectedCondition< WebElement >
  2. ExpectedCondition< WebDriver >
  3. ExpectedCondition< Boolean >
  4. ExpectedCondition< Alert >

We will not look at each of these Expected Conditions one by one in detail.

ExpectedCondition < WebElement >

This ExpectedCondtions uses the WebElement as a parameter. Then the Explicit Wait is performed until the specified expected condition is fulfilled or the specified wait duration is reached. When the expected condition is fulfilled, it returns the corresponding WebElement, a list of WebElements, or other relevant information based on the core implementation of the ExpectedCondition.

ExpectedCondition < WebDriver >

This allows you to wait for WebDriver-related conditions to be satisfied before moving forward with your test execution. Once the specified operations are successfully performed, the method returns the WebDriver instance, indicating that the desired conditions have been met.

ExpectedCondition < Boolean >

This represents a condition that returns a Boolean value. It is used in Explicit Waits to wait for specific conditions to be satisfied and to return a Boolean value as a result indicating whether the condition has been met or not.

ExpectedCondition < Alert >

This represents a condition to wait for the presence of an alert on a web page. This type of condition is used in Explicit Waits to wait for an alert to be present. Once the alert is present, you can interact with it using methods like accept() to accept the alert or dismiss() to dismiss it.

We have discussed the different categories of ExpectedConditions in Selenium Java. Now, Let’s explore some of the commonly used ExpectedConditions in Selenium Java to implement Explicit Waits.

Commonly used ExpectedConditions in Selenium Java

In this section, we are going to look at the static methods provided in the ExpectedConditions class in Java. We will see how to use them in a practical way by writing Selenium Test Scripts.

elementToBeClickable Method

It is a method of ExpectedCondition that waits for an element to be clickable. This is especially useful in scenarios where elements may take some time to load, become enabled, or change state based on certain conditions.

Method Category – ExpectedCondition< WebElement >

Syntax –

presenceOfElementLocated​ Method

This method is used to wait for the presence of a specific element on a web page. It checks whether the element is available in the DOM (Document Object Model) of the page or not. If the element is found, the method returns the WebElement, indicating that the element is now ready for further interactions in your automation testing. In other words, it ensures that the element is loaded and can be accessed before proceeding with any actions on it.

Method Category – ExpectedCondition< WebElement >

Syntax-

visibilityOfElementLocated​ Method

This method waits for an element to be both present in the DOM and visible on the web page before proceeding with the test execution. Similar to the presenceOfElementLocated​ Method, this also checks if the element is present in the DOM of the page. But this method does one thing extra as this checks if the element also has a non-zero size, meaning it is visible to the user on the web page or not. If the element meets both conditions, the method returns the WebElement, indicating that the element is now visible and is available for further interactions.

Method Category – ExpectedCondition< WebElement >

Syntax-

visibilityOfAllElementsLocatedBy​ Method

This method is similar to the visibilityOfElementLocated​ Method. The only difference is that it waits for all elements matching a specific locator to be both present in the DOM and visible on the web page before proceeding with the test execution.

Method Category – ExpectedCondition< WebElement >

Syntax-

Let’s take an example to understand the above method.
(We will implement various tests using the LambdaTest’s Demo Website)

In the above program, we started by importing the necessary modules and then created a WebDriver instance(e.g. ChromeDriver in our case) to navigate to our desired website.

navigate to our desired website

Now, let’s look at the different ExpectedConditions methods used in the program above program.

presenceOfElementLocated: We waited for an element with the ID attribute “username” to be present in the DOM of the webpage. Once the element was found, it returned a reference to the WebElement, and we used the sendKeys method to input the text “xyz@lambdatest” into the corresponding input field. Similarly, we found the element with the ID attribute “password” and entered the text “LambdaTest” into the input field.

navigate to our desired website

elementToBeClickable: This method waited for the element with the link text “Blogs” to become clickable. Once the element was clickable, it returned a reference to the WebElement, and we utilized the click method to navigate to the “Blogs” section.

elementToBeClickable

element with the link text

visibilityOfElementLocated: We waited for an element with the specified XPath expression to become visible on the webpage. Once it became visible, the method returned the WebElement reference, and we extracted the text of the element and printed it.

visibilityOfElementLocated

visibilityOfAllElementsLocatedBy: In this case, we waited for all elements matching the given XPath expression to be visible on the webpage. Once all elements were visible, the method returned a list of WebElement references. We then iterated through the list and printed the text of each element.

visibilityOfAllElementsLocatedBy

frameToBeAvailableAndSwitchToIt​ Method

This method is used to wait for a frame to be available on a web page and then switch the driver’s focus to that frame.

Method Category – ExpectedCondition< WebDriver >

Syntax-

elementToBeSelected​ Method

This method is used to wait until the WebElement is selected with a specified locator. It is handy when you deal with web pages that involve user interactions, such as selecting options from dropdown menus, clicking checkboxes, or choosing radio buttons.

Method Category – ExpectedCondition< Boolean >

Syntax-

invisibilityOfElementLocated​ Method

This method is used to wait for a web element to become invisible or hidden on the web page before proceeding further. It continuously checks if the element is present in the DOM and visible on the page. If the element becomes invisible, it returns ‘true’, indicating that the element is no longer visible.

Method Category – ExpectedCondition< Boolean >

Syntax-

textToBe Method

This method is used to wait for the text of a web element to be equal to a given string (passes as a parameter) before proceeding further.

Method Category – ExpectedCondition

Syntax-

Let’s understand textToBe method with an example.

In the above program, we use the Explicit Wait concept with Selenium WebDriverWait and ExpectedConditions textToBe method to wait for a specific element on the webpage to contain the given text “Login Selenium Playground”. Since the given text does not match the text located using the XPath expression in the specified time. Therefore a TimeoutException is caught, and the WebDriver is correctly closed after waiting for 5 seconds.

TimeoutException is caught

Now. we pass “Login to Selenium Playground” as a given text. In this case, the given text matches with the text located using the XPath expression. Therefore the WebDriver properly closed before 5 seconds.

textToBePresentInElementLocated​ Method

This method is used to check whether a given text (passed as a parameter to the method) is present in the visible text of a web element or not.

If the given text is present in the web element, it returns a boolean value ‘true’ or otherwise returns ‘false’.

Method Category – ExpectedCondition< Boolean >

Syntax-

Let’s understand the textToBePresentInElementLocated​ method with an example.

In this case, the given text “Selenium” matches with the text located using the XPath expression. Therefore the WebDriver properly closed before 5 seconds.

 the given text Selenium

textToBePresentInElementValue​ Method

This method is used to check whether a given text (passed as a parameter to the method) is present in the specified elements value attribute or not.

If the given text is present, it returns a boolean value ‘true’ or otherwise returns ‘false’.

Method Category – ExpectedCondition< Boolean >

Syntax-

titleContains​ Method

This method is used to check whether a given title/text is present in the current page title or the title of a WebElement or not.

If the given text is present in the current page title, it returns a boolean value ‘true’ or otherwise returns ’false’.

Method Category – ExpectedCondition< Boolean >

Syntax-

Let’s understand the titleContains method with an example.

Output:

Output

In this case, the given title “Selenium Playground” matches the title of the webpage. Therefore it returns true and the result is printed. (As you can see in the Output)

titleIs​ Method

This method is used to check whether a web page title is exactly match with the given string(passed as a parameter) or not.

If the given text matches with the title of the webpage then it returns a boolean value ‘true’ or otherwise ‘false’.

Method Category – ExpectedCondition< Boolean >

Syntax-

urlContains​ Method

This method is used to check whether a URL of a webpage contain a specific string or given string (passed as a parameter) or not.

If the given string is present in the URL then it returns a boolean value ‘true’ or otherwise ‘false’.

Method Category – ExpectedCondition< Boolean >

Syntax-

Let’s understand the urlContains method with an example.

Output:

In this case, the URL of the webpage contains automation-demos. Therefore it returns true and the result is printed. (As you can see in the Output)

it returns true and the result is printed

Now, we passed the “xyz” and since the URL of the webpage didn’t contain “xyz”. Therefore it returns false and the result is printed. (As you can see in the Output)

Output:

urlToBe​ Method

This method is used to check whether the URL of a web page exactly matches a specific URL/given URL or not.

If the given string exactly matches the URL of the webpage, it returns a boolean value ‘true’ or otherwise returns ‘false’.

Method Category – ExpectedCondition< Boolean >

Syntax-

alertIsPresent Method

This method is used to wait for an alert dialog to be present on a web page and then perform actions like accepting or dismissing the alert as part of your test flow. This method is particularly useful when dealing with web pages that use JavaScript-based alert boxes to show messages, prompts, or confirmations to the user.

Method Category – ExpectedCondition< Alert >

Syntax-

Let’s take an example for better understanding.

Output:

In the above program, we use the Explicit Wait concept with Selenium WebDriverWait to check if an alert is present on a web page. It waits for a maximum of 5 seconds for the alert to appear. The result is then printed to the console, indicating whether the alert is present or not.
If the alert is present, its text is retrieved and printed to the console. The alert is then accepted by clicking the “OK” button.

(As you can see in the image below)

alert is then accepted by ok button

alert is then accepted by ok button

Finally, the code closes the web browser, ensuring smooth execution of the test regardless of the presence of the alert.

You can also check out the article, ExpectedConditions in Selenium, for more detailed information and related examples.

Info Note

Run the Explicit Wait Command using WebDriverWait on a Selenium Cloud Grid of 3000+ real devices! Try LambdaTest Today!

If you would be interested in deep diving on the Wait Commands in Selenium, chekck out tutorial video on our YouTube channel.

Limitations of Selenium WebDriverWait

Selenium WebDriverWait is a class in Java used for handling synchronization automation testing. However, it does have some limitations. Let’s explore them.

  • Limited to Web-Based Applications: Selenium WebDriverWait is specifically designed for web-based applications and cannot be used for other types of applications. For example – Mobile.
  • Dependency on Web Elements: Selenium WebDriverWait relies on web elements to determine the synchronization condition. If the desired web element is not present or accessible, it can cause the wait to fail or result in a longer wait time.
  • Performance Impact: Using Selenium WebDriverWait excessively or with long wait times can impact the performance of test execution. Therefore, it is important to find the right balance between wait times and test execution speed.
  • Difficulties with Dynamic Elements: While Selenium WebDriverWait can handle some dynamic elements, it may encounter challenges with highly dynamic web pages where elements frequently change or are added/removed dynamically.
  • Lack of Native Support for Asynchronous Operations: Selenium WebDriverWait may not handle all types of asynchronous operations or AJAX requests by default. Additional customization may be required to handle such scenarios.

Conclusion

In this article, we have explored the concept of Explicit Wait using the Selenium WebDriverWait class in Java. We have introduced WebDriverWait and discussed its advantages. Next, we dived into the Explicit Waits using the WebDriverWait class. After that, we discussed ExpectedConditions available in Selenium Java and provided detailed explanations with real-world examples to enhance your understanding. We have addressed some limitations associated with using Explicit Waits in Selenium.

Our primary goal with this article is to offer a comprehensive and reader-friendly resource that equips you with the knowledge and guidance needed to implement WebDriverWait in your Selenium test automation projects effectively.

Frequently Asked Questions (FAQs)

What are ExpectedConditions in Selenium WebDriverWait?

ExpectedConditions in Selenium WebDriverWait are pre-defined conditions that can be used to wait for specific element states or events. These conditions include element visibility, presence, clickability, text presence, and many more.

Can I create custom wait conditions with Selenium WebDriverWait?

Yes, you can create custom wait conditions with Selenium WebDriverWait. This allows you to handle specific scenarios or synchronization requirements that are not covered by the built-in expected conditions.

How to handle timeouts with Selenium WebDriverWait?

Selenium WebDriverWait allows you to set a timeout duration, specifying the maximum amount of time the script should wait for the desired condition to be met. If the condition is not met within the specified timeout, a TimeoutException is thrown. However, you can handle this exception to implement error handling or retry mechanisms as needed.

Is Selenium WebDriverWait compatible with different web browsers?

Yes, Selenium WebDriverWait is compatible with various web browsers like Chrome, Firefox, Safari, etc supported by Selenium which makes it a reliable choice for cross-browser automation testing.

Author Profile Author Profile Author Profile

Author’s Profile

Upendra Prasad Mahto

Upendra is a multidimensional individual with a strong interest in technology and innovation. He has set out to create a digital environment with a solid foundation in computer science fundamentals and a deep interest in programming. His knowledge enables him to address problems logically and analytically. He has an inherent ability for content creation, seamlessly weaving words together to create attractive articles.

Blogs: 12



linkedintwitter

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free