【问题标题】:Python Selenium Wait till Any TextPython Selenium 等到任何文本
【发布时间】:2016-02-13 03:36:21
【问题描述】:

我有一个 selenium 测试,需要等到任何文本被填充,而不是精确的文本字符串匹配......

我了解到text_to_be_present_in_elementtext_to_be_present_in_element_value 可用于此类用途,但我可能需要正则表达式之类的东西,而不是完全匹配。

有人可以分享吗?

# 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>'))

【问题讨论】:

  • 有没有办法在不创建自定义 EC 的情况下做到这一点,可能类似于: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"]')) ???(这是实际的 XPath)

标签: python regex selenium


【解决方案1】:

没问题。做一个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

用法:

wait = WebDriverWait(driver, 10)
wait.until(wait_for_text_to_match((By.ID, "myid"), r"regex here"))

【讨论】:

  • 有没有办法在不创建自定义 EC 的情况下做到这一点,可能类似于: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"]')) ???(这是实际的 XPath)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-03-27
  • 1970-01-01
  • 2017-04-24
  • 2020-12-05
  • 2021-01-18
  • 2021-09-05
  • 1970-01-01
相关资源
最近更新 更多