Selenium webdriver python中新ExpectedCondition类的语法

Selenium webdriver python中新ExpectedCondition类的语法,python,selenium,selenium-webdriver,Python,Selenium,Selenium Webdriver,我将SeleniumWebDriver与python一起使用。 我想创建一个显式的等待弹出窗口出现。不幸的是,EC模块的常用方法不包括针对该问题的现成解决方案。在搜索了许多其他帖子后,我发现我必须写下自己的EC条件,并且 .until(new ExpectedCondition(){*条件及其返回参数*} 我很难找到关于正确编写此代码所使用的确切语法的文档。这里有一个java示例:。是否有人可以指向相关文档(通常不是关于等待,而是关于创建新的EC),或者如果我刚刚链接到java代码,请帮我编写p

我将SeleniumWebDriver与python一起使用。 我想创建一个显式的等待弹出窗口出现。不幸的是,EC模块的常用方法不包括针对该问题的现成解决方案。在搜索了许多其他帖子后,我发现我必须写下自己的EC条件,并且
.until(new ExpectedCondition(){*条件及其返回参数*}

我很难找到关于正确编写此代码所使用的确切语法的文档。这里有一个java示例:。是否有人可以指向相关文档(通常不是关于等待,而是关于创建新的EC),或者如果我刚刚链接到java代码,请帮我编写python版本。
非常感谢

我没有机会尝试,但我想你可以使用:

在webdriver/support/expected_conditions.py中,
alert_存在
的定义如下:

class alert_is_present(object):
    """ Expect an alert to be present."""
    def __init__(self):
        pass

    def __call__(self, driver):
        try:
            alert = driver.switch_to_alert()
            alert.text
            return alert
        except NoAlertPresentException:
            return False
你可以把它写得更简单

def alert_is_present(driver):
    try:
        alert = driver.switch_to_alert()
        alert.text
        return alert
    except NoAlertPresentException:
        return False

这可能会让您了解如何编写此类条件。

如果要等待任意条件,则根本不必使用
ExpectedCondition
。您只需将函数传递给
方法,直到
方法:

from selenium.webdriver.support.ui import WebDriverWait

def condition(driver):
    ret = False
    # ...
    # Actual code to check condition goes here and should
    # set `ret` to a truthy value if the condition is true
    # ...
    return ret

WebDriverWait(driver, 10).until(condition)
上述代码将反复调用
条件
,直到以下任一项为真:

  • 条件
    返回一个计算结果为true的值

  • 已过10秒(在这种情况下会引发异常)


将我的新条件定义为类时效果非常好,正如您在上文中针对alert_is_present方法所示。谢谢!我删除了我提到的问题,因为这是我定义类时的一个简单错误。只想指出带有示例条件的源代码:
from selenium.webdriver.support.ui import WebDriverWait

def condition(driver):
    ret = False
    # ...
    # Actual code to check condition goes here and should
    # set `ret` to a truthy value if the condition is true
    # ...
    return ret

WebDriverWait(driver, 10).until(condition)