Selenium Waits: Deep Dive 🚀

 Selenium Waits: Deep Dive 🚀

Waits in Selenium are essential for handling dynamic web pages where elements load at different times. Using proper waits prevents issues like NoSuchElementException, ElementNotVisibleException, or StaleElementReferenceException.


1. Types of Waits in Selenium

Selenium provides three types of waits:

  1. Implicit Wait - Waits for all elements globally.
  2. Explicit Wait - Waits for a specific condition on a specific element.
  3. Fluent Wait - Similar to explicit wait but with polling.

1. Implicit Wait

🔹 Implicit wait applies globally and makes Selenium wait for a set time before throwing an exception if an element is not found.
🔹 Once set, it affects all findElement() and findElements() calls.

Syntax:

java

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

Example:

java

CopyEdit

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import java.time.Duration;

 

public class ImplicitWaitExample {

    public static void main(String[] args) {

        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");

        WebDriver driver = new ChromeDriver();

 

        // Set implicit wait for 10 seconds

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

 

        driver.get("https://www.google.com");

 

        // This will wait up to 10 seconds before throwing an exception

        driver.findElement(By.name("q")).sendKeys("Selenium Waits");

 

        driver.quit();

    }

}

🔹 Best Use Case: When elements are expected to load within a predictable time.
🔹 Limitation: Cannot wait for specific conditions like visibility, clickability, etc.


2. Explicit Wait

🔹 Explicit wait is used to wait for specific conditions like:

  • Element is visible
  • Element is clickable
  • Element contains text
  • Element disappears, etc.
🔹 It is implemented using WebDriverWait.

Syntax:

java

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

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

Example:

java

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.ExpectedConditions;

import org.openqa.selenium.support.ui.WebDriverWait;

import java.time.Duration;

 

public class ExplicitWaitExample {

    public static void main(String[] args) {

        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");

        WebDriver driver = new ChromeDriver();

 

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

 

        // Explicit wait for the element to be visible

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

        WebElement button = wait.until(ExpectedConditions.elementToBeClickable(By.id("submit")));

 

        button.click();

 

        driver.quit();

    }

}

Commonly Used Expected Conditions:

Condition

Description

visibilityOfElementLocated(By.locator)

Waits for the element to be visible.

elementToBeClickable(By.locator)

Waits until the element is clickable.

presenceOfElementLocated(By.locator)

Waits until the element is present in the DOM.

textToBePresentInElementLocated(By.locator, "text")

Waits for specific text to appear.

invisibilityOfElementLocated(By.locator)

Waits until the element disappears.



3. Fluent Wait

🔹 Fluent Wait is similar to Explicit Wait but allows:

  • Custom polling frequency (e.g., check every 500ms).
  • Ignore specific exceptions (e.g., NoSuchElementException).

Syntax:

java

FluentWait<WebDriver> wait = new FluentWait<>(driver)

    .withTimeout(Duration.ofSeconds(15))   // Maximum wait time

    .pollingEvery(Duration.ofMillis(500))  // Check every 500ms

    .ignoring(NoSuchElementException.class); // Ignore exception

 

WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("exampleId")));

Example:

java

import org.openqa.selenium.*;

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.function.Function;

 

public class FluentWaitExample {

    public static void main(String[] args) {

        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");

        WebDriver driver = new ChromeDriver();

 

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

 

        // Fluent wait implementation

        Wait<WebDriver> wait = new FluentWait<>(driver)

           .withTimeout(Duration.ofSeconds(15))   // Max wait time

           .pollingEvery(Duration.ofMillis(500))  // Poll every 500ms

           .ignoring(NoSuchElementException.class); // Ignore NoSuchElementException

 

        WebElement element = wait.until(new Function<WebDriver, WebElement>() {

            public WebElement apply(WebDriver driver) {

                return driver.findElement(By.id("exampleId"));

            }

        });

 

        element.click();

 

        driver.quit();

    }

}

🔹 Best Use Case: When element loading time is unpredictable and needs frequent checks.


4. Differences Between Implicit, Explicit, and Fluent Waits

Feature

Implicit Wait

Explicit Wait

Fluent Wait

Scope

Applies to all elements

Specific elements

Specific elements

Condition-Based?

No

Yes

Yes

Polling Mechanism?

No

No

Yes (Customizable)

Exception Handling

No

Yes

Yes

Use Case

General element loading

Conditional waits (e.g., visibility)

Unpredictable wait time



5. Which Wait Should You Use?

Scenario

Recommended Wait

Waiting for elements that take time to load globally

Implicit Wait

Waiting for a specific element with a specific condition

Explicit Wait

Handling slow, unpredictable elements with retries

Fluent Wait


Best Practice

  • Use Implicit Wait for default page loading.
  • Use Explicit Wait for waiting on specific elements.
  • Use Fluent Wait for elements that load randomly.

6. Handling Timeouts in Selenium

If an element doesn’t appear within the wait time, Selenium throws a TimeoutException.

Example Handling:

java

try {

    WebElement button = wait.until(ExpectedConditions.elementToBeClickable(By.id("submit")));

    button.click();

} catch (TimeoutException e) {

    System.out.println("Element not found within the specified time!");

}


7. Using Thread.sleep() (NOT Recommended)

You might think of using Thread.sleep() to delay execution:

java

Thread.sleep(5000);  // Waits for 5 seconds

🚨 Why is this bad?

  • Slows down test execution unnecessarily.
  • Not dynamic (waits even if the element loads instantly).
  • Better Alternative: Use Explicit Wait instead.

🔥 Conclusion

Use the right wait depending on the scenario
Avoid Thread.sleep() unless debugging
Combine waits for best performance

🚀 Want help implementing waits in a Selenium framework like TestNG or Cucumber? Let me know! 🚀

 

 

https://otieu.com/4/9433883
https://otieu.com/4/9433883