You need to enable JavaScript to run this app. 如何为Explicit Waits设置判断条件,实现元素查找超时时的分支逻辑?
优惠活动
大模型
产品
解决方案
定价
更多

如何为Explicit Waits设置判断条件,实现元素查找超时时的分支逻辑?

你可以通过捕获WebDriverWait抛出的TimeoutException超时异常来实现分支判断逻辑,具体实现步骤如下:

1. 先导入依赖的异常类

from selenium.common.exceptions import TimeoutException

2. 完整实现代码

# 提前初始化结果存储列表
test1_records = []
test2_records = []

try:
    # 等待目标元素加载,5秒未找到则抛出TimeoutException
    element = WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.CLASS_NAME, "CLASS NAME")))
    # 元素查找成功,执行CASE A逻辑
    items = select_getPage_1(driver)
    for item in items:
        record = get_result_flipkart(item)
        if record:
            test1_records.append(record)
except TimeoutException:
    # 捕获到超时异常,说明元素未找到,执行CASE B逻辑
    items = select_getPage_2(driver)
    for item in items:
        record = get_result_flipkart(item)
        if record:
            test2_records.append(record)

注意事项

  • 定位表达式拼写错误、页面渲染速度慢超出等待时长,都会触发超时异常,你可以根据需求在except块中添加调试日志,区分异常原因
  • 如果需要处理其他类型的异常(比如选择器格式错误抛出的InvalidSelectorException),可以额外新增对应的except分支单独处理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 19:57:01