Selenium Waits

Modern websites load content slowly through JavaScript and background requests. A script that runs faster than the page loads tries to click elements that do not exist yet. Waits pause the script until an element becomes ready.

Diagram: A Race Between Script And Page

Time -->
Script:   [find element]---[click]
Page:     [loading......][element appears]
                ^
          Without a wait, the click happens
          before the element exists.

Implicit Wait

Implicit wait tells the entire WebDriver session to wait a set number of seconds before throwing a not-found error. You set this once at the start of a script.

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

Every findElement() call now waits up to ten seconds before giving up, checking repeatedly during that window.

Explicit Wait

Explicit wait targets one specific element and one specific condition, giving finer control than implicit wait.

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(15));
WebElement loginBtn = wait.until(ExpectedConditions.elementToBeClickable(By.id("login-btn")));
loginBtn.click();

This code waits up to fifteen seconds for the login button to become clickable, then clicks it immediately once ready.

Common Expected Conditions

  • visibilityOfElementLocated() waits until an element appears and is visible.
  • elementToBeClickable() waits until an element is visible and enabled.
  • presenceOfElementLocated() waits until an element exists in the HTML, even if hidden.
  • textToBePresentInElement() waits until specific text appears inside an element.

Fluent Wait

Fluent wait adds polling frequency and custom exceptions to ignore during the wait period. It suits pages where elements appear at unpredictable intervals.

Wait<WebDriver> fluentWait = new FluentWait<>(driver)
    .withTimeout(Duration.ofSeconds(30))
    .pollingEvery(Duration.ofSeconds(5))
    .ignoring(NoSuchElementException.class);

WebElement element = fluentWait.until(driver -> driver.findElement(By.id("dynamic-content")));

This waits up to thirty seconds, checking every five seconds, and ignores errors while the element is still missing.

Never Mix Implicit And Explicit Waits

Combining both wait types on the same driver often creates unpredictable delays. Selenium documentation recommends picking one strategy per project, with explicit wait as the safer modern choice.

Avoid Thread.sleep()

Thread.sleep() pauses a script for a fixed time regardless of page state. A five-second sleep wastes time on fast pages and still fails on slow pages. Explicit waits solve both problems by checking conditions repeatedly instead of guessing a fixed duration.

Leave a Comment

Your email address will not be published. Required fields are marked *