Fluent Wait

Estimated reading: 6 minutes 19 views

Overview

In Selenium WebDriver, Fluent Wait is a more advanced type of wait that allows you to define the frequency with which the WebDriver checks for a condition to be met. Unlike the regular Explicit Wait, which waits for a specific condition for a fixed amount of time, Fluent Wait gives you more control over the polling interval (how often the WebDriver checks the condition) and the exceptions to ignore while waiting.

Fluent Wait is particularly useful in scenarios where you expect the condition to be met after a series of retries, or when dealing with slow-loading elements that might not be immediately available.

Syntax

The Fluent Wait is implemented using the FluentWait class, combined with a Duration for the timeout and a polling interval. You can also specify which exceptions to ignore while waiting.

Here’s the syntax:

				
					// Create a FluentWait instance with a timeout of 30 seconds,
// polling every 5 seconds, and ignoring NoSuchElementException
FluentWait<WebDriver> wait = new FluentWait<>(driver)
    .withTimeout(Duration.ofSeconds(30))  // Total time to wait
    .pollingEvery(Duration.ofSeconds(5))  // Interval between checks
    .ignoring(NoSuchElementException.class); // Ignore specific exceptions

// Wait until the element is visible and return it
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("exampleId")));
				
			

In this syntax:

  • withTimeout(Duration): Specifies the maximum amount of time to wait for the condition to be met.
  • pollingEvery(Duration): Defines how often the condition should be checked during the wait period.
  • ignoring(Class): Specifies which exceptions should be ignored during the wait period (e.g., NoSuchElementException, StaleElementReferenceException).

Usage

  1. Waiting for an Element to be Visible:

    A common use case for Fluent Wait is to wait for an element to become visible within a specific time frame and check its visibility at regular intervals.

  2. Waiting for Element to Be Clickable:

    If you want to wait for an element to become clickable with a custom polling interval:

				
					// Create a FluentWait instance with a timeout of 20 seconds,
// polling every 3 seconds, and ignoring ElementNotInteractableException
FluentWait<WebDriver> wait = new FluentWait<>(driver)
    .withTimeout(Duration.ofSeconds(20))    // Timeout
    .pollingEvery(Duration.ofSeconds(3))    // Polling interval
    .ignoring(ElementNotInteractableException.class); // Ignore specific exceptions

// Wait until the element is clickable, and then click the button
WebElement button = wait.until(ExpectedConditions.elementToBeClickable(By.id("submitButton")));
button.click();
				
			

This waits for up to 20 seconds, checking every 3 seconds if the element is clickable.

Example

Here’s an example of how to use Fluent Wait in practice to handle dynamic content where the element’s visibility might take varying amounts of time to load:

				
					import org.openqa.selenium.By;
import org.openqa.selenium.ElementNotInteractableException;
import org.openqa.selenium.NoSuchElementException;
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.FluentWait;

import java.time.Duration;

public class FluentWaitExample {
    public static void main(String[] args) {
        // Set path to the ChromeDriver executable
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");

        // Initialize WebDriver
        WebDriver driver = new ChromeDriver();

        // Open a webpage
        driver.get("https://www.example.com");

        // Create a FluentWait instance with a timeout of 30 seconds,
        // polling every 5 seconds, and ignoring NoSuchElementException
        FluentWait<WebDriver> wait = new FluentWait<>(driver)
            .withTimeout(Duration.ofSeconds(30))   // Total time to wait
            .pollingEvery(Duration.ofSeconds(5))   // Poll every 5 seconds
            .ignoring(NoSuchElementException.class); // Ignore certain exceptions

        // Wait until the element is visible and return it
        WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("dynamicElement")));

        // Print the element's text after it's found
        System.out.println("Element Text: " + element.getText());

        // Close the browser
        driver.quit();
    }
}
				
			

In this example, Selenium will attempt to find the dynamicElement every 5 seconds for up to 30 seconds. If the element is not found after 30 seconds, it will throw a timeout exception. However, if the element is not yet interactable, the exception NoSuchElementException is ignored and the search continues.

Importance

  1. Customizable Polling Interval: Fluent Wait allows you to define the frequency with which the condition is checked, providing flexibility for slow or intermittently available elements.

  2. Handling Dynamic Content: Fluent Wait is very useful when dealing with web applications that load content dynamically (e.g., with AJAX) and where elements might appear at varying times.

  3. Handling Multiple Exceptions: Fluent Wait gives you the ability to ignore specific exceptions while waiting. For example, if an element is temporarily missing, you can configure Fluent Wait to ignore the NoSuchElementException and continue polling.

  4. Optimized Resource Usage: By controlling the polling frequency, Fluent Wait can help optimize resource usage. Frequent polling with short intervals can prevent excessive CPU or memory usage in case of slow elements.

Limitations

  1. Performance Considerations: Although Fluent Wait is customizable, setting very short polling intervals can cause performance issues or excessive CPU usage, especially on pages with many elements or complex interactions.

  2. Complexity: While Fluent Wait provides a lot of flexibility, it can increase the complexity of the script, particularly in scenarios where multiple wait conditions are required for different elements.

  3. Not Always Necessary: Fluent Wait may not be necessary for simple cases where Explicit Wait is sufficient. Using Fluent Wait in situations where polling intervals are not required can add unnecessary complexity.

Differences from Implicit and Explicit Wait

  • Fluent Wait offers the most flexibility with customizable polling intervals and the ability to ignore specific exceptions during the wait period.
  • Explicit Wait waits for a specific condition to be met but does not allow for fine control over polling intervals or ignored exceptions.
  • Implicit Wait is a global setting applied to all elements and cannot be customized per element or condition.

Conclusion

Fluent Wait in Selenium WebDriver is a powerful waiting mechanism that offers fine-grained control over waiting for elements. It is ideal for situations where elements take varying times to become visible or interactable, and for dealing with dynamic content or intermittent failures. Fluent Wait’s ability to specify custom polling intervals and handle exceptions provides greater flexibility compared to other wait methods like Implicit Wait or Explicit Wait.

When using Fluent Wait, it’s important to balance its flexibility with performance considerations. Overusing it or setting very frequent polling intervals can lead to inefficiency, so it should be used where necessary for handling complex scenarios.

By mastering Fluent Wait, testers can write more reliable and stable Selenium automation scripts, particularly for modern web applications with dynamic and frequently changing content.

Key Points:

  • Fluent Wait provides full control over timeout, polling frequency, and exception handling.
  • Useful for handling slow-loading or dynamic elements.
  • More flexible than Implicit Wait and Explicit Wait.
  • Ideal for complex or highly dynamic web pages.

Leave a Comment

Share this Doc

Fluent Wait

Or copy link

CONTENTS