Expected Conditions
Use built-in expected conditions for common wait scenarios like visibility, clickability, and text presence.
Expected Conditions are pre-built wait conditions for common scenarios. They handle the complexity of checking element states, so you don’t have to write custom logic for every wait.
Visibility Conditions
import org.openqa.selenium.support.ui.WebDriverWait;import org.openqa.selenium.support.ui.ExpectedConditions;import java.time.Duration;
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
// Wait for element to be visible (present + displayed)WebElement element = wait.until( ExpectedConditions.visibilityOfElementLocated(By.id("content")));
// Wait for already-found element to be visibleWebElement foundElement = driver.findElement(By.id("popup"));wait.until(ExpectedConditions.visibilityOf(foundElement));
// Wait for all matching elements to be visibleList<WebElement> items = wait.until( ExpectedConditions.visibilityOfAllElementsLocatedBy(By.className("item")));
// Wait for element to become invisiblewait.until(ExpectedConditions.invisibilityOfElementLocated(By.id("loading")));
// Wait for element with text to become invisiblewait.until(ExpectedConditions.invisibilityOfElementWithText( By.className("status"), "Loading..."));from selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, 10)
# Wait for element to be visible (present + displayed)element = wait.until( EC.visibility_of_element_located((By.ID, "content")))
# Wait for already-found element to be visiblefound_element = driver.find_element(By.ID, "popup")wait.until(EC.visibility_of(found_element))
# Wait for all matching elements to be visibleitems = wait.until( EC.visibility_of_all_elements_located((By.CLASS_NAME, "item")))
# Wait for element to become invisiblewait.until(EC.invisibility_of_element_located((By.ID, "loading")))
# Wait for element with text to become invisiblewait.until(EC.invisibility_of_element_located((By.CLASS_NAME, "status")))const { until } = require('selenium-webdriver');
// Wait for element to be visibleconst element = await driver.wait( until.elementLocated(By.id('content')), 10000);await driver.wait(until.elementIsVisible(element), 10000);
// Wait for element to be invisible/removedawait driver.wait(until.elementIsNotVisible(element), 10000);
// Wait for element to be stale (removed from DOM)await driver.wait(until.stalenessOf(element), 10000);using OpenQA.Selenium.Support.UI;
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
// Wait for element to be visible (present + displayed)IWebElement element = wait.Until( ExpectedConditions.ElementIsVisible(By.Id("content")));
// Wait for already-found element to be visibleIWebElement foundElement = driver.FindElement(By.Id("popup"));wait.Until(d => foundElement.Displayed);
// Wait for all matching elements to be visibleIList<IWebElement> items = wait.Until( ExpectedConditions.VisibilityOfAllElementsLocatedBy(By.ClassName("item")));
// Wait for element to become invisiblewait.Until(ExpectedConditions.InvisibilityOfElementLocated(By.Id("loading")));Clickability Conditions
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
// Wait for element to be clickable (visible + enabled)WebElement button = wait.until( ExpectedConditions.elementToBeClickable(By.id("submit-btn")));button.click();
// Wait for element reference to be clickableWebElement link = driver.findElement(By.linkText("Continue"));wait.until(ExpectedConditions.elementToBeClickable(link)).click();
// Pattern: Wait then clickwait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(".action-btn"))).click();wait = WebDriverWait(driver, 10)
# Wait for element to be clickable (visible + enabled)button = wait.until( EC.element_to_be_clickable((By.ID, "submit-btn")))button.click()
# Wait for element reference to be clickablelink = driver.find_element(By.LINK_TEXT, "Continue")wait.until(EC.element_to_be_clickable(link)).click()
# Pattern: Wait then clickwait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".action-btn"))).click()// Wait for element to be enabledconst button = await driver.findElement(By.id('submit-btn'));await driver.wait(until.elementIsEnabled(button), 10000);await button.click();
// Combined: locate, wait for clickable, clickconst element = await driver.wait( until.elementLocated(By.id('submit-btn')), 10000);await driver.wait(until.elementIsVisible(element), 10000);await driver.wait(until.elementIsEnabled(element), 10000);await element.click();WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
// Wait for element to be clickable (visible + enabled)IWebElement button = wait.Until( ExpectedConditions.ElementToBeClickable(By.Id("submit-btn")));button.Click();
// Wait for element reference to be clickableIWebElement link = driver.FindElement(By.LinkText("Continue"));wait.Until(ExpectedConditions.ElementToBeClickable(link)).Click();
// Pattern: Wait then clickwait.Until(ExpectedConditions.ElementToBeClickable(By.CssSelector(".action-btn"))).Click();Presence Conditions
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
// Wait for element to be present in DOM (may not be visible)WebElement element = wait.until( ExpectedConditions.presenceOfElementLocated(By.id("hidden-data")));
// Wait for all matching elements to be presentList<WebElement> elements = wait.until( ExpectedConditions.presenceOfAllElementsLocatedBy(By.className("item")));System.out.println("Found " + elements.size() + " items");
// Wait for nested elementWebElement parent = driver.findElement(By.id("container"));WebElement child = wait.until( ExpectedConditions.presenceOfNestedElementLocatedBy( parent, By.className("child") ));wait = WebDriverWait(driver, 10)
# Wait for element to be present in DOM (may not be visible)element = wait.until( EC.presence_of_element_located((By.ID, "hidden-data")))
# Wait for all matching elements to be presentelements = wait.until( EC.presence_of_all_elements_located((By.CLASS_NAME, "item")))print(f"Found {len(elements)} items")
# Wait for nested elementparent = driver.find_element(By.ID, "container")child = wait.until( EC.presence_of_element_located((By.CLASS_NAME, "child")))// Wait for element to be present in DOMconst element = await driver.wait( until.elementLocated(By.id('hidden-data')), 10000);
// Wait for multiple elementsconst elements = await driver.wait( until.elementsLocated(By.className('item')), 10000);console.log(`Found ${elements.length} items`);WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
// Wait for element to be present in DOM (may not be visible)IWebElement element = wait.Until( ExpectedConditions.ElementExists(By.Id("hidden-data")));
// Wait for all matching elements to be presentIList<IWebElement> elements = wait.Until( ExpectedConditions.PresenceOfAllElementsLocatedBy(By.ClassName("item")));Console.WriteLine($"Found {elements.Count} items");Text Conditions
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
// Wait for element to contain specific textboolean hasText = wait.until( ExpectedConditions.textToBePresentInElementLocated( By.id("status"), "Complete" ));
// Wait for element's value attribute to contain textboolean hasValue = wait.until( ExpectedConditions.textToBePresentInElementValue( By.id("result"), "Success" ));
// Wait for exact text matchWebElement element = driver.findElement(By.id("message"));wait.until(ExpectedConditions.textToBe(By.id("message"), "Done!"));wait = WebDriverWait(driver, 10)
# Wait for element to contain specific texthas_text = wait.until( EC.text_to_be_present_in_element( (By.ID, "status"), "Complete" ))
# Wait for element's value attribute to contain texthas_value = wait.until( EC.text_to_be_present_in_element_value( (By.ID, "result"), "Success" ))
# Wait for exact text match# (use a custom condition or text_to_be_present_in_element)// Custom text conditionasync function textToBe(locator, expectedText) { return async (driver) => { try { const element = await driver.findElement(locator); const text = await element.getText(); return text === expectedText; } catch (e) { return false; } };}
// Wait for textawait driver.wait(textToBe(By.id('status'), 'Complete'), 10000);
// Wait for text to containawait driver.wait(async () => { const el = await driver.findElement(By.id('status')); const text = await el.getText(); return text.includes('Complete');}, 10000);WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
// Wait for element to contain specific textbool hasText = wait.Until( ExpectedConditions.TextToBePresentInElementLocated( By.Id("status"), "Complete" ));
// Wait for element's value attribute to contain textbool hasValue = wait.Until( ExpectedConditions.TextToBePresentInElementValue( By.Id("result"), "Success" ));Frame and Window Conditions
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
// Wait for frame to be available and switch to itwait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id("myframe")));// Now interacting with frame content
// Switch back to main contentdriver.switchTo().defaultContent();
// Wait for frame by name or indexwait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt("frameName"));wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(0)); // First frame
// Wait for new window/tabString mainWindow = driver.getWindowHandle();driver.findElement(By.id("open-new-window")).click();
wait.until(ExpectedConditions.numberOfWindowsToBe(2));for (String handle : driver.getWindowHandles()) { if (!handle.equals(mainWindow)) { driver.switchTo().window(handle); break; }}wait = WebDriverWait(driver, 10)
# Wait for frame to be available and switch to itwait.until(EC.frame_to_be_available_and_switch_to_it((By.ID, "myframe")))# Now interacting with frame content
# Switch back to main contentdriver.switch_to.default_content()
# Wait for frame by name or indexwait.until(EC.frame_to_be_available_and_switch_to_it("frameName"))wait.until(EC.frame_to_be_available_and_switch_to_it(0)) # First frame
# Wait for new window/tabmain_window = driver.current_window_handledriver.find_element(By.ID, "open-new-window").click()
wait.until(EC.number_of_windows_to_be(2))for handle in driver.window_handles: if handle != main_window: driver.switch_to.window(handle) break// Wait for frame and switchconst frame = await driver.wait( until.ableToSwitchToFrame(By.id('myframe')), 10000);
// Switch back to main contentawait driver.switchTo().defaultContent();
// Wait for new windowconst mainWindow = await driver.getWindowHandle();await driver.findElement(By.id('open-new-window')).click();
await driver.wait(async () => { const handles = await driver.getAllWindowHandles(); return handles.length === 2;}, 10000);
const handles = await driver.getAllWindowHandles();const newWindow = handles.find(h => h !== mainWindow);await driver.switchTo().window(newWindow);WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
// Wait for frame to be available and switch to itwait.Until(ExpectedConditions.FrameToBeAvailableAndSwitchToIt(By.Id("myframe")));// Now interacting with frame content
// Switch back to main contentdriver.SwitchTo().DefaultContent();
// Wait for new window/tabstring mainWindow = driver.CurrentWindowHandle;driver.FindElement(By.Id("open-new-window")).Click();
wait.Until(d => d.WindowHandles.Count == 2);foreach (string handle in driver.WindowHandles){ if (handle != mainWindow) { driver.SwitchTo().Window(handle); break; }}Alert Conditions
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
// Wait for alert to appearAlert alert = wait.until(ExpectedConditions.alertIsPresent());
// Get alert textString alertText = alert.getText();System.out.println("Alert says: " + alertText);
// Accept (OK) the alertalert.accept();
// Or dismiss (Cancel) the alert// alert.dismiss();
// Handle prompt (alert with input)Alert prompt = wait.until(ExpectedConditions.alertIsPresent());prompt.sendKeys("My input");prompt.accept();wait = WebDriverWait(driver, 10)
# Wait for alert to appearalert = wait.until(EC.alert_is_present())
# Get alert textalert_text = alert.textprint(f"Alert says: {alert_text}")
# Accept (OK) the alertalert.accept()
# Or dismiss (Cancel) the alert# alert.dismiss()
# Handle prompt (alert with input)prompt = wait.until(EC.alert_is_present())prompt.send_keys("My input")prompt.accept()// Wait for alert to appearawait driver.wait(until.alertIsPresent(), 10000);const alert = await driver.switchTo().alert();
// Get alert textconst alertText = await alert.getText();console.log(`Alert says: ${alertText}`);
// Accept (OK) the alertawait alert.accept();
// Or dismiss (Cancel)// await alert.dismiss();
// Handle promptconst prompt = await driver.switchTo().alert();await prompt.sendKeys('My input');await prompt.accept();WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
// Wait for alert to appearIAlert alert = wait.Until(ExpectedConditions.AlertIsPresent());
// Get alert textstring alertText = alert.Text;Console.WriteLine($"Alert says: {alertText}");
// Accept (OK) the alertalert.Accept();
// Or dismiss (Cancel) the alert// alert.Dismiss();
// Handle prompt (alert with input)IAlert prompt = wait.Until(ExpectedConditions.AlertIsPresent());prompt.SendKeys("My input");prompt.Accept();Expected Conditions Reference
| Condition | Waits For |
|---|---|
visibilityOfElementLocated | Element visible on page |
invisibilityOfElementLocated | Element not visible |
elementToBeClickable | Element visible and enabled |
presenceOfElementLocated | Element in DOM |
textToBePresentInElement | Element contains text |
alertIsPresent | JavaScript alert appears |
frameToBeAvailableAndSwitchToIt | Frame loads and switches |
numberOfWindowsToBe | Specific window count |
stalenessOf | Element removed from DOM |
attributeToBe | Attribute has value |
urlContains | URL contains text |
titleContains | Page title contains text |
Java: ExpectedCondition No Longer Uses Guava (4.51+)
Since Selenium 4.51 the Java client no longer depends on Guava, and ExpectedCondition<T> extends only java.util.function.Function<WebDriver, T>. Before that it also extended Guava’s com.google.common.base.Function.
Most code is unaffected. Passing ExpectedConditions.* or a lambda to wait.until(...) compiles exactly as before. What breaks:
- Variables, fields or method signatures typed as
com.google.common.base.Functionthat hold anExpectedCondition. - Helpers that call Guava-only methods on a condition, or chain it with Guava’s
Functions/Predicatesutilities. - Code that used Guava classes (
ImmutableList,Lists,Preconditions) without declaring Guava, because it used to arrive transitively through Selenium.
The fix is mechanical:
// Before (fails to compile on 4.51+)import com.google.common.base.Function;Function<WebDriver, WebElement> ready = ExpectedConditions.elementToBeClickable(By.id("save"));
// After: use ExpectedCondition, or the JDK Functionimport org.openqa.selenium.support.ui.ExpectedCondition;ExpectedCondition<WebElement> ready = ExpectedConditions.elementToBeClickable(By.id("save"));If you still use Guava elsewhere in the project, declare it as an explicit dependency instead of relying on Selenium to bring it in. Python, JavaScript and C# are not affected.
Note: Search your Java test code for
import com.google.common.base.Functionbefore upgrading to 4.51. It is the one import that turns a routine version bump into a compile failure.
Next Steps
- Fluent Waits - Advanced wait configuration
- Explicit Waits - Basic wait usage
- Alerts and Popups - Work with dialogs
- iFrames Handling - Frame switching
Finished this lesson?
Mark it complete to track your progress through the course. Saved in this browser only.
Copy-paste recipes
- Wait for a CSS Animation or Transition to Finish
Wait until a sliding drawer, modal or accordion has stopped moving before clicking, using the Web Animations API with a position-stability fallback.
- Wait for a Loading Spinner to Disappear
Wait for an overlay or spinner to be gone before interacting, including the case where it never appeared.
Errors you may hit
- ElementClickInterceptedException
Fix Selenium ElementClickInterceptedException (ElementClickInterceptedError in JS): overlays, cookie banners, sticky headers and animations blocking your click.
- ElementNotInteractableException
Fix Selenium ElementNotInteractableException (ElementNotInteractableError in JS): hidden elements, duplicate matches, zero-size inputs and custom controls.
- NoSuchFrameException
Fix Selenium NoSuchFrameException (NoSuchFrameError in JS): iframes that load late, wrong frame names or indexes, nested frames and re-rendered iframes.
- NoSuchWindowException
Fix Selenium NoSuchWindowException (NoSuchWindowError in JS): closed tabs, self-closing popups, stale window handles and switching before a new tab opens.