Sometimes, built-in wait conditions in Selenium do not fit your needs. Custom expected conditions let you create your own rules to wait for specific things on a webpage.
Custom expected conditions in 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) # return True or element if condition met, else False or None return element if element.text == 'Expected Text' else False
Custom expected conditions are classes or functions that implement the __call__ method.
The __call__ method receives the driver and returns a truthy value when the condition is met, or False/None otherwise.
class TextIsPresent: def __init__(self, locator, text): self.locator = locator self.text = text def __call__(self, driver): element = driver.find_element(*self.locator) return element if self.text in element.text else False
def element_has_attribute(locator, attribute, value): def _predicate(driver): element = driver.find_element(*locator) return element if element.get_attribute(attribute) == value else False return _predicate
This test script opens a webpage, waits up to 10 seconds for a button with ID 'submit-button' to become enabled, then prints confirmation.
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait class ButtonEnabled: def __init__(self, locator): self.locator = locator def __call__(self, driver): button = driver.find_element(*self.locator) return button if button.is_enabled() else False # Setup driver (example with Chrome) driver = webdriver.Chrome() driver.get('https://example.com') wait = WebDriverWait(driver, 10) button_locator = (By.ID, 'submit-button') # Wait until the button is enabled button = wait.until(ButtonEnabled(button_locator)) print('Button is enabled:', button.is_enabled()) driver.quit()
Always return the element or a truthy value when the condition is met, so you can use it after waiting.
Return False or None if the condition is not met to keep waiting.
Custom conditions help make your tests more flexible and readable.
Custom expected conditions let you wait for exactly what you need on a page.
They are classes or functions with a __call__ method that Selenium calls repeatedly.
Use them to improve test reliability and clarity.