You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Selenium多wait条件失效:WebDriverWait未等待元素可见直接执行怎么办

问题根源

你的代码逻辑存在原理性错误:EC.visibility_of_element_located() 调用后返回的是预期条件函数对象,而非元素可见性的布尔判断结果。在Python中,非空函数对象的布尔值默认为True,因此你写的(EC.visibility_of_element_located(xxx)) or (EC.visibility_of_element_located(xxx)) 会直接返回第一个真值(第一个EC函数对象),WebDriverWait的until方法判断返回值为真就会直接结束等待,根本不会执行元素可见性的校验逻辑,所以不管目标元素是否出现都会直接往下执行,最终导致断言失败。

正确实现方案

有两种常用写法可以实现「等待两个元素任意一个可见」的需求:

写法1:lambda内主动调用EC函数执行判断

给每个EC条件后传入until方法传入的driver对象(也就是lambda的参数x),执行后拿到实际的判断结果:

element = WebDriverWait(self.driver, 30).until(
    lambda x: EC.visibility_of_element_located((By.ID, "export_errors_button"))(x) or
              EC.visibility_of_element_located((By.ID, "finish_button"))(x)
)
# 补充:id属性本身是单个字符串,不需要split()拆分
assert "finish_button" in element.get_attribute('id')

写法2:用Selenium内置any_of组合条件(Selenium 4及以上版本支持)

Selenium已经提供了多条件组合的工具方法,不需要手动写lambda逻辑,代码更易读:

# 提前导入any_of
from selenium.webdriver.support.expected_conditions import any_of

element = WebDriverWait(self.driver, 30).until(
    any_of(
        EC.visibility_of_element_located((By.ID, "export_errors_button")),
        EC.visibility_of_element_located((By.ID, "finish_button"))
    )
)
assert element.get_attribute('id') == "finish_button"

内容的提问来源于stack exchange,提问作者shaw2thefloor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 11:09:03