在Python中对正则表达式执行WebDriverWait()或类似检查 [英] Perform a WebDriverWait() or similar check on a Regular Expression in Python

查看:306
本文介绍了在Python中对正则表达式执行WebDriverWait()或类似检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to be able to perform something similar to a WebDriverWait(), i.e:

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

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

...for a regular expression, where it waits for an allotted amount of time before failing. I am aware I could do something, such as...

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

...或者在上述示例中,我可以将搜索替换为匹配.此方法的问题是,如果对象..(1)尚未加载,或者..(2)仍在更改为预期的状态,则它将失败.我可以做类似的事情...

...or I could replace search with match in the above example. The problem with this method is it'll fail if the object.. (1) hasn't loaded yet or.. (2) is still in the process of changing to what's expected. I could do something like...

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 语句是否评估为true.这可能适合模块或类.我想知道的是,对于Selenium WebDriver,是否有更优雅的解决方案(Python)来处理我不知道的问题.

...where it checks every second for 60 seconds to see if the assert statement has evaluated to true. This could fit into a module or class. What I'm wondering is if there is a more elegant solution, in Python for the Selenium WebDriver, to handling this that I'm unaware of.

推荐答案

如果您查看,您会很容易创建自定义条件:

If you look into what an "Expected Condition" is, you would find it easy to make a custom one:

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}")
)

这篇关于在Python中对正则表达式执行WebDriverWait()或类似检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆