1. Selenium自动化测试入门指南
刚接触Web自动化测试时,我花了整整两周才弄明白如何让Selenium稳定运行。现在回想起来,如果当时有人能系统地讲解这些核心要点,至少能节省80%的调试时间。本文将分享基于Python的Selenium实战经验,重点解决三个问题:环境配置的坑点、元素定位的进阶技巧、以及如何构建健壮的测试脚本。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 环境搭建与基础配置
2.1 浏览器驱动管理
安装浏览器驱动是新手最容易卡住的环节。以Chrome为例,需要特别注意驱动版本与浏览器版本的匹配:
python复制from selenium import webdriver
from selenium.webdriver.chrome.service import Service
# 推荐使用Service对象管理驱动路径
service = Service('/path/to/chromedriver')
driver = webdriver.Chrome(service=service)
常见问题排查表:
| 错误现象 | 可能原因 | 解决方案 |
|---|---|---|
| SessionNotCreatedException | 浏览器与驱动版本不匹配 | 查看chrome://version获取精确版本号 |
| WebDriverException | 驱动文件未加入PATH | 使用绝对路径或配置环境变量 |
| TimeoutError | 驱动未正确启动 | 检查杀毒软件是否拦截 |
提示:使用webdriver-manager库可自动处理驱动版本问题:
python复制from webdriver_manager.chrome import ChromeDriverManager driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
2.2 等待策略优化
元素加载异步问题会导致90%的测试失败。除了显式等待(WebDriverWait),更推荐使用Expected Conditions:
python复制from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
wait = WebDriverWait(driver, 10)
element = wait.until(EC.presence_of_element_located((By.ID, "dynamic-content")))
三种等待方式对比:
- 硬性等待(time.sleep):仅限调试使用
- 隐式等待(implicitly_wait):全局设置但不够精准
- 显式等待:针对特定元素的最佳实践
3. 元素定位进阶技巧
3.1 XPath与CSS选择器实战
当元素没有ID或class时,定位器组合使用能大幅提高稳定性:
python复制# 组合CSS选择器
driver.find_element(By.CSS_SELECTOR, "div.form-group > input[name='username']")
# XPath轴定位
driver.find_element(By.XPATH, "//button[contains(text(),'提交')]")
driver.find_element(By.XPATH, "//input[@type='text']/following-sibling::div")
定位策略优先级建议:
- 首选By.ID(最快最稳定)
- 次选By.CSS_SELECTOR(性能优于XPath)
- 复杂结构考虑XPath轴定位
3.2 动态元素处理技巧
对于动态生成的元素,需要特殊处理方式:
python复制# 处理StaleElementReferenceException
def safe_click(element_locator):
for _ in range(3):
try:
wait.until(EC.element_to_be_clickable(element_locator)).click()
break
except StaleElementReference
