Selenium 显式等待

Selenium 显式等待 WebDriverWait

一、为什么抛弃 time.sleep()

python 复制代码
time.sleep(3)

硬等待:强制卡死3秒,不管页面是否加载完成

缺点:

  1. 元素提前加载好了,依然要等 → 脚本运行慢
  2. 元素加载超过3秒 → 直接抛找不到元素异常

✅ 显式等待 WebDriverWait:循环判断元素条件,满足条件立刻放行;超过超时时间才报错。灵活高效,工作必用。

二、需要导入包

python 复制代码
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

三、标准模板(背诵!固定写法)

python 复制代码
# 参数1:driver对象;参数2:超时总时间(秒);参数3:轮询间隔(多久检查一次,默认0.5s)
wait = WebDriverWait(driver, 10, 0.5)

# until:直到满足条件
ele = wait.until(
    EC.presence_of_element_located( (By.XPATH, "//input[@id='kw']") )
)

⚠️ 注意:() 里面是元组,两个参数必须括号包起来!

四、常用 expected_conditions 条件(高频)

  1. presence_of_element_located:元素存在DOM中(html加载出来,不一定可见)
  2. visibility_of_element_located:元素可见(推荐大多数场景,能看到才能点击输入)
  3. element_to_be_clickable:元素可点击(按钮可用,无遮挡,优先用于按钮)
  4. text_to_be_present_in_element:元素文本包含指定内容

五、完整可运行示例(百度搜索)

python 复制代码
from selenium import webdriver
from selenium.webdriver.edge.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

web_driver = webdriver.Edge(service=Service(r"D:\Software\edgedriver_win64\msedgedriver.exe"))
web_driver.get("https://www.baidu.com")
web_driver.maximize_window()

# 实例化等待对象,最长等待10秒
wait = WebDriverWait(web_driver, 10)

# 等待搜索框可见,找到元素
search_input = wait.until(
    EC.visibility_of_element_located( (By.ID, "kw") )
)
search_input.send_keys("显式等待学习")

# 等待按钮可点击
search_btn = wait.until(
    EC.element_to_be_clickable( (By.ID, "su") )
)
search_btn.click()

# 等待结果文本出现
wait.until(
    EC.text_to_be_present_in_element( (By.XPATH, "//h3"), "显式等待学习" )
)

web_driver.quit()

六、隐式等待(补充了解,不推荐混用)

python 复制代码
driver.implicitly_wait(10)

全局设置,整个会话生效;显式、隐式不要一起使用,容易出现奇怪超时bug,企业主流只用【显式等待】

七、常见报错

  1. TimeoutException:规定时间内,条件始终不满足
    排查:xpath写错 / 元素被遮挡 / 在iframe内 / 页面跳转没加载完成
  2. 忘记元组括号:EC.xxx(By.ID,"kw") ❌ → EC.xxx( (By.ID,"kw") ) ✅
相关推荐
火云代理1 天前
同一个网站,有的网络能打开、有的打不开?认识 IPv4 与 IPv6 的访问差异
服务器·网络·网络协议·tcp/ip·测试工具·php·状态模式
freejackman5 天前
【工程化】从“单兵作战”到“多引擎架构”:基于门面模式的重构实战
大数据·数据库·hive·sql·测试工具·设计模式·架构
坐吃山猪6 天前
Python22-PostMan调试MCP
测试工具·postman·mcp
测试界的小码农6 天前
【 AI Agent 软件测试实战(05):任务规划与状态管理,让 Agent 学会拆解复杂测试任务】
人工智能·测试工具
和粒科技8 天前
热重分析仪TG 309 Libra Classic
测试工具
ClouGence9 天前
不搭 Selenium 或 Playwright,怎么测试公司的内网业务?
selenium·测试
螺丝钉tina14 天前
[Playwright] [02]常用命令与调试:Debug UI、Mode和 Trace Viewer
开发语言·javascript·测试工具·ui·自动化
梧桐16815 天前
14天、31个缺陷、28个测试脚本—用 Claude Code 完成第三方软件测试
人工智能·测试工具
mewowaBc16 天前
postman使用细则
测试工具·postman·偏差
光影62716 天前
Unittest单元测试基础速记
测试工具·单元测试·json·测试覆盖率