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 TextEquals:
def __init__(self, locator, text):
self.locator = locator
self.text = text
def __call__(self, driver):
element = driver.find_element(*self.locator)
if element.text == self.text:
return element
else:
return False
def test_wait_for_text():
driver = webdriver.Chrome()
try:
driver.get('https://example.com/dynamic-text')
wait = WebDriverWait(driver, 10)
element = wait.until(TextEquals((By.ID, 'status-message'), 'Completed'))
assert element.text == 'Completed', f"Expected text 'Completed' but got '{element.text}'"
except TimeoutException:
assert False, "Timed out waiting for text 'Completed' in element with ID 'status-message'"
finally:
driver.quit()This script defines a custom expected condition class TextEquals that waits for an element's text to match exactly a given string.
The __call__ method is used by Selenium's WebDriverWait to repeatedly check the element's text until it matches or timeout occurs.
The test function test_wait_for_text opens the browser, navigates to the page, and waits up to 10 seconds for the text 'Completed' to appear in the element with ID 'status-message'.
If the text matches, it asserts success; if it times out, it asserts failure with a clear message.
Finally, the browser is closed to clean up resources.