Python Selenium WebDriver. Writing my own expected condition

Looks like this topic misses an example of a Custom Expected Condition.

It is actually pretty easy. First of all, what is an Expected Condition in Python selenium bindings:

There is a big set of built-in expected condition classes.

Let’s work through example. Let’s say we want to wait until an element’s text will start with a desired text:

from selenium.webdriver.support import expected_conditions as EC

class wait_for_text_to_start_with(object):
    def __init__(self, locator, text_):
        self.locator = locator
        self.text = text_

    def __call__(self, driver):
        try:
            element_text = EC._find_element(driver, self.locator).text
            return element_text.startswith(self.text)
        except StaleElementReferenceException:
            return False

Usage:

WebDriverWait(driver, 10).until(wait_for_text_to_start_with((By.ID, 'myid'), "Hello, World!"))

Leave a Comment