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.