0
0
Selenium Pythontesting~5 mins

Explicit waits (WebDriverWait) in Selenium Python

Choose your learning style9 modes available
Introduction

Explicit waits help your test wait for a specific condition before moving on. This avoids errors when elements take time to appear or change.

Waiting for a button to become clickable before clicking it.
Waiting for a text message to appear after submitting a form.
Waiting for a page element to load after navigation.
Waiting for a popup or alert to show up before interacting.
Waiting for a loading spinner to disappear before checking results.
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((By.LOCATOR_TYPE, 'locator_value')))

WebDriverWait creates a wait object with a max time to wait.

until() pauses test until the condition is true or timeout happens.

Examples
Waits up to 10 seconds for the button with ID 'submit-btn' to be clickable.
Selenium Python
wait = WebDriverWait(driver, 10)
wait.until(EC.element_to_be_clickable((By.ID, 'submit-btn')))
Waits up to 5 seconds for an element with class 'message' to be visible.
Selenium Python
wait = WebDriverWait(driver, 5)
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, '.message')))
Sample Program

This script opens a webpage and waits up to 10 seconds for a login button to be clickable. It prints a success message if clickable, or an error if not.

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 (using Chrome as example)
driver = webdriver.Chrome()
driver.get('https://example.com')

try:
    wait = WebDriverWait(driver, 10)
    # Wait for the login button to be clickable
    login_button = wait.until(EC.element_to_be_clickable((By.ID, 'login-btn')))
    print('Login button is clickable.')
except Exception as e:
    print('Login button not clickable:', e)
finally:
    driver.quit()
OutputSuccess
Important Notes

Always import expected_conditions as EC for readability.

Use tuples like (By.ID, 'value') as locators inside conditions.

Explicit waits are better than fixed sleeps because they wait only as long as needed.

Summary

Explicit waits pause test until a condition is met or timeout occurs.

Use WebDriverWait with expected conditions for reliable element interaction.

This helps tests handle slow loading or dynamic page changes smoothly.