Sometimes, you need to wait for something special on a webpage before continuing your test. Custom wait conditions let you tell the test exactly what to wait for.
0
0
Custom wait conditions in Selenium Python
Introduction
Waiting for a specific text to appear inside an element.
Waiting for a button to become clickable after some animation.
Waiting for a custom attribute to change value on an element.
Waiting for multiple elements to be visible at the same time.
Waiting for a loading spinner to disappear before proceeding.
Syntax
Selenium Python
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC class CustomCondition: def __init__(self, locator): self.locator = locator def __call__(self, driver): element = driver.find_element(*self.locator) if element.text == 'Ready': return element else: return False
The custom condition is a class with a __call__ method that Selenium calls repeatedly.
Return the element or True when the condition is met; return False to keep waiting.
Examples
This waits until the element's text is exactly 'Ready'.
Selenium Python
class TextIsReady: def __init__(self, locator): self.locator = locator def __call__(self, driver): element = driver.find_element(*self.locator) return element.text == 'Ready'
This waits until a specific attribute of an element matches the expected value.
Selenium Python
class AttributeChanged: def __init__(self, locator, attribute, expected_value): self.locator = locator self.attribute = attribute self.expected_value = expected_value def __call__(self, driver): element = driver.find_element(*self.locator) return element.get_attribute(self.attribute) == self.expected_value
Sample Program
This test opens a page, waits up to 10 seconds for the element with ID 'status' to have text 'Ready', then prints the text.
Selenium Python
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait class TextIsReady: def __init__(self, locator): self.locator = locator def __call__(self, driver): element = driver.find_element(*self.locator) if element.text == 'Ready': return element else: return False # Setup driver (example with Chrome) driver = webdriver.Chrome() driver.get('https://example.com/wait_test') locator = (By.ID, 'status') wait = WebDriverWait(driver, 10) # Use custom wait condition ready_element = wait.until(TextIsReady(locator)) print(f"Element text is: {ready_element.text}") driver.quit()
OutputSuccess
Important Notes
Custom wait conditions help when built-in waits are not enough.
Always return False or None to keep waiting, and a truthy value to stop waiting.
Use descriptive class names to keep your tests clear.
Summary
Custom wait conditions let you wait for exactly what you need.
Create a class with a __call__ method that returns True or the element when ready.
Use WebDriverWait with your custom condition to pause your test smartly.