Explicit Wait with WebDriverWait

Wait for a Specific Condition

import java.time.Duration;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

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

driver.findElement(By.id("login-btn")).click();
WebElement welcome = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("welcome")));
System.out.println(welcome.getText());

Example

Output (the element appeared after about 0.9 s, so the wait returned then):

Run LoginWaitTest.main()

Example output

Welcome, Priya

Common ExpectedConditions

ConditionUse
visibilityOfElementLocated(by)element present and visible (most used)
elementToBeClickable(by)visible and enabled, before a click
presenceOfElementLocated(by)in the DOM, maybe hidden
invisibilityOfElementLocated(by)spinner or loader is gone
textToBePresentInElementLocated(by, "1")cart count changed to 1
urlContains("/account"), titleContains("Cart")navigation finished
alertIsPresent(), frameToBeAvailableAndSwitchToIt(by)alerts and frames
numberOfElementsToBe(by, 24)all product cards loaded

When the Wait Times Out

Example

If the condition is still false after 10 s, Selenium throws:

Run LoginWaitTest.main()

Example output

org.openqa.selenium.TimeoutException: Expected condition failed: waiting for visibility of element located by By.id: welcome (tried for 10 second(s) with 500 milliseconds interval)

Tip: This message tells you exactly what was not true. It is much easier to debug than a sleep followed by NoSuchElementException.