Skip to main content
 首页 » 编程设计

python之在 Python 中对正则表达式执行 WebDriverWait() 或类似检查

2024年08月26日29mayingbao

我希望能够执行类似于 WebDriverWait() 的操作,即:

WebDriverWait(driver, 60).until( 
    expected_conditions.text_to_be_present_in_element((By.XPATH, "//tr[5]/td[11]/div"), "1.000000") 
) 

...对于正则表达式,它在失败之前等待分配的时间。我知道我可以做一些事情,例如......

assert re.search(r"[0,1]{1}.[0-9]{6}", driver.find_element_by_xpath("//tr[5]/td[11]/div").text) 

...或者我可以将上面示例中的 search 替换为 ma​​tch。此方法的问题是如果对象.. (1) 尚未加载或.. (2) 仍在更改为预期内容的过程中,它将失败。我可以做类似...

for x in range (1,60): 
    try: 
        assert re.search(r"[0,1]{1}.[0-9]{6}", driver.find_element_by_xpath("//tr[5]/td[11]/div").text) 
    except AssertionError: 
        if x < 60: 
            time.sleep(1) 
        else: 
            raise AssertionError 

...它每秒检查一次,持续 60 秒,以查看 assert 语句的计算结果是否为真。这可以适合模块或类。我想知道是否有更优雅的解决方案(在 Python 中用于 Selenium WebDriver)来处理这个我不知道的问题。

请您参考如下方法:

如果你查看 what an "Expected Condition" is ,您会发现定制一个很容易:

import re 
 
from selenium.webdriver.support.expected_conditions import _find_element 
 
 
class text_match(object): 
    def __init__(self, locator, regexp): 
        self.locator = locator 
        self.regexp = regexp 
 
    def __call__(self, driver): 
        element_text = _find_element(driver, self.locator).text 
        return re.search(self.regexp, element_text) 

用法:

WebDriverWait(driver, 60).until( 
    text_match((By.XPATH, "//tr[5]/td[11]/div"), r"[0,1]{1}.[0-9]{6}") 
)