0
0
Selenium Pythontesting~15 mins

Custom wait conditions in Selenium Python - Build an Automation Script

Choose your learning style9 modes available
Wait for a specific element's text to change before proceeding
Preconditions (2)
Step 1: Navigate to the target web page URL
Step 2: Locate the element with id 'status-message'
Step 3: Wait until the text of the element changes from 'Loading...' to 'Complete'
Step 4: Verify that the element's text is exactly 'Complete'
✅ Expected Result: The test waits until the element's text changes to 'Complete' and then verifies it successfully
Automation Requirements - Selenium with Python
Assertions Needed:
Assert the element's text is 'Complete' after waiting
Best Practices:
Use WebDriverWait with a custom expected condition
Avoid using time.sleep for waiting
Use By.ID locator for element identification
Handle TimeoutException properly
Automated Solution
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
from selenium.common.exceptions import TimeoutException

class text_to_be_changed:
    def __init__(self, locator, old_text):
        self.locator = locator
        self.old_text = old_text

    def __call__(self, driver):
        element = driver.find_element(*self.locator)
        if element.text != self.old_text:
            return element
        else:
            return False

def test_wait_for_text_change():
    driver = webdriver.Chrome()
    driver.get('https://example.com/dynamic-text')

    locator = (By.ID, 'status-message')
    old_text = 'Loading...'

    wait = WebDriverWait(driver, 10)
    try:
        element = wait.until(text_to_be_changed(locator, old_text))
        assert element.text == 'Complete', f"Expected text 'Complete' but got '{element.text}'"
    except TimeoutException:
        assert False, "Timed out waiting for text to change"
    finally:
        driver.quit()

The text_to_be_changed class is a custom wait condition that waits until the text of the element located by locator changes from old_text. It returns the element when the text changes, otherwise returns False to keep waiting.

In the test function, we open the browser and navigate to the page. We define the locator for the element with id status-message and the old text Loading....

We use WebDriverWait with our custom condition to wait up to 10 seconds for the text to change. If the text changes, we assert it is exactly Complete. If the wait times out, we fail the test with a clear message.

Finally, we close the browser to clean up.

Common Mistakes - 3 Pitfalls
Using time.sleep() instead of explicit waits
Hardcoding XPath locators that are brittle
Not handling TimeoutException
Bonus Challenge

Now add data-driven testing with 3 different old texts to wait for changes

Show Hint