Selenium 预期条件 - 可以使用“或"吗? [英] Selenium Expected Conditions - possible to use 'or'?

查看:46
本文介绍了Selenium 预期条件 - 可以使用“或"吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 Selenium 2/WebDriver 与 Python API 一起使用,如下所示:

I'm using Selenium 2 / WebDriver with the Python API, as follows:

from selenium.webdriver.support import expected_conditions as EC

# code that causes an ajax query to be run

WebDriverWait(driver, 10).until( EC.presence_of_element_located( \
    (By.CSS_SELECTOR, "div.some_result")));

我想等待要么返回结果(div.some_result)未找到"字符串.那可能吗?种类:

I want to wait for either a result to be returned (div.some_result) or a "Not found" string. Is that possible? Kind of:

WebDriverWait(driver, 10).until( \
    EC.presence_of_element_located( \
         (By.CSS_SELECTOR, "div.some_result")) \
    or 
    EC.presence_of_element_located( \
         (By.CSS_SELECTOR, "div.no_result")) \
);

我意识到我可以使用 CSS 选择器(div.no_result, div.some_result)来做到这一点,但是有没有办法使用 Selenium 预期条件方法来做到这一点?

I realise I could do this with a CSS selector (div.no_result, div.some_result), but is there a way to do it using the Selenium expected conditions method?

推荐答案

我是这样做的:

class AnyEc:
    """ Use with WebDriverWait to combine expected_conditions
        in an OR.
    """
    def __init__(self, *args):
        self.ecs = args
    def __call__(self, driver):
        for fn in self.ecs:
            try:
                if fn(driver): return True
            except:
                pass

然后称之为...

from selenium.webdriver.support import expected_conditions as EC
# ...
WebDriverWait(driver, 10).until( AnyEc(
    EC.presence_of_element_located(
         (By.CSS_SELECTOR, "div.some_result")),
    EC.presence_of_element_located(
         (By.CSS_SELECTOR, "div.no_result")) ))

显然,同样实现一个 AllEc 类是微不足道的.

Obviously it would be trivial to also implement an AllEc class likewise.

铌.try: 块很奇怪.我很困惑,因为有些 EC 返回 true/false,而其他 EC 会为 False 抛出异常.异常被 WebDriverWait 捕获,所以我的 AnyEc 事情产生了奇怪的结果,因为第一个抛出异常意味着 AnyEc 没有进行下一个测试.

Nb. the try: block is odd. I was confused because some ECs return true/false while others will throw exceptions for False. The Exceptions are caught by WebDriverWait so my AnyEc thing was producing odd results because the first one to throw an exception meant AnyEc didn't proceed to the next test.

这篇关于Selenium 预期条件 - 可以使用“或"吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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