The ExpectedConditions class helps wait for certain things to happen on a web page before continuing. This avoids errors when elements are not ready yet.
ExpectedConditions class in Selenium Java
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.condition(locator));Replace condition with the specific wait condition you want, like elementToBeClickable or visibilityOfElementLocated.
The locator is how you find the element, for example By.id("submit").
wait.until(ExpectedConditions.elementToBeClickable(By.id("submit")));wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("message")));wait.until(ExpectedConditions.titleContains("Welcome"));This test opens a login page, waits for the username field to appear, enters text, waits for the login button to be clickable, clicks it, then waits for a welcome message to show and prints it.
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 WaitExample { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); driver.get("https://example.com/login"); WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); // Wait until the username field is visible WebElement username = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("username"))); username.sendKeys("testuser"); // Wait until the login button is clickable WebElement loginButton = wait.until(ExpectedConditions.elementToBeClickable(By.id("loginBtn"))); loginButton.click(); // Wait until the welcome message appears WebElement welcomeMsg = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("welcomeMessage"))); System.out.println(welcomeMsg.getText()); driver.quit(); } }
Always use ExpectedConditions with WebDriverWait to avoid errors from elements not ready yet.
Set a reasonable timeout to avoid waiting too long or too short.
Use the right condition for your need, like visibility, clickability, or presence.
ExpectedConditions helps wait for web page elements or states before acting.
Use it with WebDriverWait and a locator to wait safely.
This avoids errors and makes tests more reliable.