Selenium 在 Python 中结合多个预期条件

Selenium Combining multiple Expected conditions in Python

wait = (driver, 10)
wait.until(EC.presence_of_element_located((By.XPATH, '//td[@class="blah blah blah"]')))
wait.until(EC.visibility_of_element_located((By.XPATH, '//h1[text() = "yo yo"]')))

有没有一种方法可以将这两个条件组合成一行,或者说如果这两个条件都为真则只在 Selenium 中单击(),Python。

下面是为 Selenium 的 WebDriverWait 创建函数的示例:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait

# Open the website
driver.get('https://ocrdata.ed.gov/flex/Reports.aspx?type=school')

... more code ...

# Custom function for Explicit Wait
# The Export button is available before it is "clickable", need to wait
def find(driver):
    export_button = driver.find_element_by_name('ctl00$div$ucReportViewer$btnExport')
    if export_button:
        try: 
            export_button.click()
            return True
        except:
            return False
    else:
        return False

secs = 120
export_button = WebDriverWait(driver, secs).until(find)

我建议将两个元素的存在和可见性记录为单独的变量,并在函数中创建一个 if 语句,如下所示:

# Custom function for Explicit Wait
# The Export button is available before it is "clickable", need to wait
def find(driver):
    presence = EC.presence_of_element_located((By.XPATH, '//td[@class="blah blah blah"]'))
    visibility = EC.visibility_of_element_located((By.XPATH, '//h1[text() = "yo yo"]'))
    if presence and visibility:
        try: 
            # action
            return True
        except:
            return False
    else:
        return False

secs = 120
export_button = WebDriverWait(driver, secs).until(find)

我遇到了同样的问题并找到了答案! 您可以使用 EC.all_of(*expected_conditions) 检查多个预期条件,就像逻辑 AND 一样,或使用 EC.any_of(*expected_conditions) 检查逻辑 OR。

所以代码应该是这样的:

WebDriverWait(driver, 5).until(
    EC.all_of(
        EC.presence_of_element_located((By.ID, "Example")),
        EC.visibility_of_element_located((By.ID, "Example"))
    )
)

它 returns 一个 webdriver 元素的列表,所以如果你想点击一个元素,你必须 select 它的索引,添加 [i].click() 到最后。

这也意味着如果您想单击要检查的元素之外的第三个元素,您还必须将其添加到检查中,select 也一样。最后会是这样的:

WebDriverWait(driver, 5).until(
    EC.all_of(
        EC.presence_of_element_located((By.ID, "Example")),
        EC.visibility_of_element_located((By.ID, "Example")),
        EC.presence_of_element_located((By.ID, "Clickable"))
    )
)[2].click()