Tuesday, 1 August 2017

Selenium Waits: Implicit, Explicit and Fluent Wait Explained with Examples

 

Introduction

One of the most common challenges in Selenium automation testing is dealing with web elements that do not appear immediately.

Modern websites frequently use JavaScript, AJAX requests, dynamic content loading and asynchronous operations. When an automation script tries to interact with an element before it becomes available, Selenium may throw exceptions such as NoSuchElementException or ElementNotInteractableException.

Selenium waits help solve this problem by allowing automation scripts to pause execution until a specified condition is satisfied or a maximum waiting time is reached.

There are three commonly discussed wait strategies in Selenium WebDriver:

  1. Implicit Wait

  2. Explicit Wait

  3. Fluent Wait

In this tutorial, we will understand each type with practical Java examples and learn when to use them.

1. What Are Waits in Selenium?

Waits are mechanisms that control how long Selenium waits for elements or conditions during test execution.

For example, consider a login page where the submit button appears only after a JavaScript operation finishes.

Without an appropriate wait, Selenium may try to click the button before it is available.

Waits help make automation scripts more reliable when dealing with dynamic webpages.

2. Implicit Wait in Selenium

Implicit Wait instructs WebDriver to wait for a specified duration when searching for elements that are not immediately available.

Once configured, it applies globally to element-location commands for that WebDriver instance.

Syntax

driver.manage().timeouts()
      .implicitlyWait(Duration.ofSeconds(10));

Complete Example

import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class ImplicitWaitExample {

    public static void main(String[] args) {

        WebDriver driver = new ChromeDriver();

        try {
            driver.manage().timeouts()
                  .implicitlyWait(Duration.ofSeconds(10));

            driver.get("https://example.com");

            driver.findElement(By.id("username"))
                  .sendKeys("testuser");

        } finally {
            driver.quit();
        }
    }
}

Advantages of Implicit Wait

  • Easy to configure.

  • Applies to element searches throughout the session.

  • Reduces immediate failures when elements take time to appear.

Limitations

  • It is not designed to wait for specific conditions such as an element becoming clickable.

  • It applies globally rather than to one particular element.

  • Combining implicit and explicit waits can produce unpredictable total wait times.

3. Explicit Wait in Selenium

Explicit Wait instructs Selenium to wait until a specific condition becomes true or a timeout occurs.

It is particularly useful for dynamic web applications where different elements may become available at different times.

Selenium provides WebDriverWait and ExpectedConditions to implement explicit waits.

Syntax

WebDriverWait wait =
    new WebDriverWait(driver, Duration.ofSeconds(10));

wait.until(
    ExpectedConditions.visibilityOfElementLocated(
        By.id("username")
    )
);

Common ExpectedConditions

Expected ConditionPurpose
visibilityOfElementLocated()Waits until an element is visible
elementToBeClickable()Waits until an element is visible and enabled
presenceOfElementLocated()Waits until an element exists in the DOM
alertIsPresent()Waits until a JavaScript alert appears
titleContains()Waits until the page title contains specified text
invisibilityOfElementLocated()Waits until an element becomes invisible or absent
textToBePresentInElementLocated()Waits until specified text appears

Example: Wait Until an Element Is Clickable

WebDriverWait wait =
    new WebDriverWait(driver, Duration.ofSeconds(10));

WebElement loginButton = wait.until(
    ExpectedConditions.elementToBeClickable(
        By.id("login")
    )
);

loginButton.click();

Example: Wait Until an Element Is Visible

WebElement username = wait.until(
    ExpectedConditions.visibilityOfElementLocated(
        By.id("username")
    )
);

username.sendKeys("admin");

Example: Wait for Text to Appear

wait.until(
    ExpectedConditions.textToBePresentInElementLocated(
        By.id("message"),
        "Login Successful"
    )
);

Explicit Wait is generally preferred when a test needs to wait for a particular condition rather than simply waiting for an element search.

4. Fluent Wait in Selenium

Fluent Wait is a configurable form of explicit waiting.

It allows testers to define:

  • Maximum waiting time.

  • Polling interval.

  • Exceptions to ignore while waiting.

For example, you can instruct Selenium to check a condition every two seconds for a maximum of twenty seconds.

Syntax

Wait<WebDriver> wait = new FluentWait<>(driver)
    .withTimeout(Duration.ofSeconds(20))
    .pollingEvery(Duration.ofSeconds(2))
    .ignoring(NoSuchElementException.class);

Complete Java Example

import java.time.Duration;

import org.openqa.selenium.By;
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.FluentWait;
import org.openqa.selenium.support.ui.Wait;

public class FluentWaitExample {

    public static void main(String[] args) {

        WebDriver driver = new ChromeDriver();

        try {
            driver.get("https://example.com");

            Wait<WebDriver> wait = new FluentWait<>(driver)
                .withTimeout(Duration.ofSeconds(20))
                .pollingEvery(Duration.ofSeconds(2))
                .ignoring(NoSuchElementException.class);

            WebElement element = wait.until(
                d -> d.findElement(By.id("username"))
            );

            element.sendKeys("testuser");

        } finally {
            driver.quit();
        }
    }
}

The example repeatedly searches for the username field until it is found or the timeout expires.

Advantages of Fluent Wait

  • Custom polling intervals.

  • Configurable timeout.

  • Ability to ignore selected exceptions.

  • Useful for elements that appear unpredictably.

5. Difference Between Implicit, Explicit and Fluent Wait

FeatureImplicit WaitExplicit WaitFluent Wait
ScopeGlobal element searchesSpecific conditionSpecific condition
ConfigurationSimple timeoutTimeout and conditionTimeout, polling and ignored exceptions
Polling controlNoLimited/default polling configurationYes
Expected conditionsNoYesCan use custom conditions
Best suited forGeneral element searchesDynamic elements and conditionsSpecial cases needing custom polling

Which one should you use?

For most modern Selenium automation projects, explicit waits are a practical default. Fluent Wait is useful when custom polling and exception handling are required. Implicit Wait may be used for simpler element-search scenarios, but avoid combining it with explicit waits in the same test suite.

6. Common Selenium Wait Exceptions

Understanding common exceptions helps automation testers troubleshoot failures.

NoSuchElementException: Selenium cannot find the element using the supplied locator.

TimeoutException: The expected condition was not satisfied within the configured timeout.

StaleElementReferenceException: The element reference is no longer attached to the current DOM, often because the page has changed or refreshed.

ElementNotInteractableException: The element exists but cannot be interacted with in its current state.

In some cases, the correct solution is to wait for the element to become visible, enabled or clickable. For stale elements, it may be necessary to locate the element again after the DOM changes.

7. Best Practices for Selenium Waits

  1. Prefer condition-based explicit waits for dynamic elements.

  2. Avoid using Thread.sleep() as the default waiting strategy.

  3. Do not mix implicit and explicit waits unnecessarily.

  4. Use appropriate ExpectedConditions.

  5. Choose realistic timeout values based on application behaviour.

  6. Re-locate elements when the DOM changes and references become stale.

  7. Use reusable wait methods in automation frameworks.

  8. Avoid waiting for clickability when the actual requirement is only element presence or visibility.

8. Creating a Reusable Explicit Wait Method

In a professional automation framework, wait logic can be placed in a reusable utility class.

public WebElement waitForElement(By locator) {

    WebDriverWait wait =
        new WebDriverWait(driver, Duration.ofSeconds(10));

    return wait.until(
        ExpectedConditions.visibilityOfElementLocated(locator)
    );
}

This method can be reused across multiple test classes and Page Object Model components.

Frequently Asked Questions

1. What are the three types of waits in Selenium?

The commonly used types are Implicit Wait, Explicit Wait and Fluent Wait.

2. Which wait is best in Selenium?

Explicit Wait is generally a good choice because it waits for a specific condition rather than applying a global delay.

3. What is the difference between Explicit Wait and Fluent Wait?

Fluent Wait provides additional control over polling intervals and ignored exceptions. Both are condition-based waiting approaches.

4. Why should Thread.sleep() be avoided?

It pauses execution for a fixed duration regardless of whether the element is already available. This can make tests slower and less efficient.

5. Can implicit and explicit waits be used together?

Although Selenium permits both, combining them can lead to unpredictable waiting times. It is generally better to use explicit waits consistently for condition-based synchronisation.

Learn Selenium Automation Testing with Palium Skills

Palium Skills provides practical automation testing training for freshers, manual testers and working professionals.

The Selenium and Playwright training curriculum can include:

  • Selenium WebDriver with Java and Python

  • Implicit, Explicit and Fluent Wait

  • XPath and CSS Selector

  • TestNG and PyTest

  • Page Object Model and automation framework development

  • API testing and real-time projects

  • Interview preparation and career guidance

Training modes: Classroom sessions at South Kolkata and Salt Lake centres, plus instructor-led live online training for learners across India.

Contact Palium Skills

South Kolkata Centre: 1st Floor, Sheeba Bhavan, 1/22 Poddar Nagar (Near South City Mall), Kolkata – 700068.

Salt Lake Centre: 5th Floor, RDB Boulevard, Block GP, Salt Lake Electronic Complex, Kolkata – 700091.

Build your automation testing expertise with practical training from Palium Skills.

No comments:

Post a Comment

TDS on Salary: A Practical Guide for HR and Payroll Professionals

  TDS on Salary: A Complete Guide for HR and Payroll Professionals Learn how TDS on salary works in India , the role of employers, employee...