3

I have a selenium test which need to wait till any text to be populated instead an exact text string match...

I have learned that text_to_be_present_in_element, text_to_be_present_in_element_value can be used for this type of purpose but I might need something like regular expression instead of exact match.

Can anyone share is it possible?

# exact match.
from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, 10)
element = wait.until(EC.text_to_be_present_in_element((By.Id,'f_name'), '<searchstring>'))
B.Mr.W.
  • 18,910
  • 35
  • 114
  • 178
  • **Is there a way to do it without creating a custom EC, maybe something like: `wait.until(EC.text_to_be_present_in_element((By.XPATH, '//header/section//*[1]/button[.//*[contains(text(), "Follow") or contains(text(), "Follow Back") or contains(text(), "Message")]]'), ["Follow", "Follow Back", "Message"]'))` ???** (This is the actualy XPath btw) – oldboy May 08 '22 at 23:44

1 Answers1

3

No problem. Make a custom Expected Condition:

import re
from selenium.webdriver.support import expected_conditions as EC

class wait_for_text_to_match(object):
    def __init__(self, locator, pattern):
        self.locator = locator
        self.pattern = re.compile(pattern)

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

Usage:

wait = WebDriverWait(driver, 10)
wait.until(wait_for_text_to_match((By.ID, "myid"), r"regex here"))
Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • **Is there a way to do it without creating a custom EC, maybe something like: `wait.until(EC.text_to_be_present_in_element((By.XPATH, '//header/section//*[1]/button[.//*[contains(text(), "Follow") or contains(text(), "Follow Back") or contains(text(), "Message")]]'), ["Follow", "Follow Back", "Message"]'))` ???** (This is the actualy XPath btw) – oldboy May 08 '22 at 23:41