0
0
Selenium Pythontesting~5 mins

Expected conditions in Selenium Python

Choose your learning style9 modes available
Introduction

Expected conditions help your test wait for things on a web page to be ready before checking them. This stops errors caused by trying to use parts of the page too early.

Waiting for a button to appear before clicking it.
Checking if a text message shows up after submitting a form.
Waiting for a page to load before reading its title.
Ensuring an element is visible before interacting with it.
Waiting for a URL to change after clicking a link.
Syntax
Selenium Python
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(driver, timeout_in_seconds)
wait.until(EC.condition(locator))

WebDriverWait waits for a maximum time for a condition to be true.

EC.condition(locator) is the expected condition you want to check, like visibility or clickability.

Examples
Wait until the element with ID 'submit-button' is visible on the page.
Selenium Python
wait.until(EC.visibility_of_element_located((By.ID, 'submit-button')))
Wait until the element with class 'btn-primary' can be clicked.
Selenium Python
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '.btn-primary')))
Wait until the current URL contains the word 'dashboard'.
Selenium Python
wait.until(EC.url_contains('dashboard'))
Sample Program

This script opens example.com, waits up to 10 seconds for the main heading (h1) to appear, then prints its text. It closes the browser after.

Selenium Python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# Setup driver (make sure chromedriver is in PATH)
driver = webdriver.Chrome()

try:
    driver.get('https://example.com')
    wait = WebDriverWait(driver, 10)

    # Wait for the heading to be visible
    heading = wait.until(EC.visibility_of_element_located((By.TAG_NAME, 'h1')))

    print('Heading text:', heading.text)

finally:
    driver.quit()
OutputSuccess
Important Notes

Always use tuples like (By.ID, 'value') as locators inside expected conditions.

Set a reasonable timeout to avoid waiting too long or too short.

Expected conditions help make tests more reliable by syncing with the page state.

Summary

Expected conditions wait for specific page states before continuing.

Use WebDriverWait with EC to avoid errors from elements not ready yet.

Common conditions include visibility, clickability, and URL changes.