应先安装selenium和pytest-selenium,再手动匹配并配置chromedriver;driver fixture默认function级生命周期,base_url需显式指定,失败截图需启用--screenshot on且确保screenshots目录存在。

pytest-selenium 依赖安装和基础配置怎么配才不报错
pytest-selenium 本身不提供 WebDriver,它只是把 Selenium 的驱动管理、fixture 注入和 pytest 生命周期串起来。直接 pip install pytest-selenium 后,pytest 运行时大概率会报 WebDriverException: Message: invalid argument 或 No module named 'selenium' —— 因为它默认依赖 selenium 和对应浏览器驱动(如 chromedriver),但不自动安装。
实操建议:
- 先装
selenium:pip install selenium - 再装
pytest-selenium:pip install pytest-selenium - Chrome 用户必须手动下载匹配版本的
chromedriver(注意 Chrome 浏览器版本与 driver 版本对应),并确保其在$PATH中,或通过--driver-path指定路径 - 启动测试前加
--driver chrome,否则默认用firefox,而多数人本地没装 Firefox 或 geckodriver
如何用 pytest-selenium 的 fixture 控制浏览器生命周期
pytest-selenium 提供了几个关键 fixture:driver、base_url、selenium(已弃用)、live_server(配合 Django/Flask)。最常用的是 driver,但它不是“开箱即用”的全局实例 —— 它的 scope 默认是 function,每次 test 函数都会新建+销毁一个浏览器实例。
常见误区:
立即学习“Python免费学习笔记(深入)”;
- 误以为
driver是单例:其实每个 test 独立,不能靠它跨用例保持登录态 - 想复用浏览器提速?改 scope 到
class或module可以,但得自己处理 cookie 清理、页面残留状态,容易导致用例污染 -
base_urlfixture 默认值是http://localhost:8000,如果被测系统不在这个地址,必须用命令行参数覆盖:pytest --base-url https://example.com
示例:在 test 文件顶部加配置
def test_login(driver, base_url):
driver.get(f"{base_url}/login")
driver.find_element("name", "username").send_keys("admin")
driver.find_element("name", "password").send_keys("123")
driver.find_element("xpath", "//button[@type='submit']").click()
为什么 pytest-selenium 的截图和失败日志经常找不到或不生效
pytest-selenium 内置了 selenium-screenshot 和 pytest-html 集成能力,但默认不开启截图,也不自动保存失败时的页面源码或截图 —— 这是人为设计的轻量策略,不是 bug。
要让失败时自动截图,必须显式启用:
- 加命令行参数:
--screenshot on(可选值:on/off/only-on-failure) - 截图保存路径默认是
./screenshots/,但该目录需存在,否则报错FileNotFoundError;建议运行前执行mkdir -p screenshots - 若用了
--html=report.html,截图链接才会嵌入 HTML 报告;否则截图只存文件,无上下文关联 - 注意:截图仅对
driverfixture 生效,如果你在 test 中手动 new 了webdriver.Chrome(),那些实例不会被 hook,也不会截图
pytest-selenium 和纯 Selenium + pytest 的区别在哪
核心差异在于“谁管 driver 实例”和“谁负责 teardown”。用纯 Selenium 写法,你得自己写 fixture 管理 driver 生命周期、处理异常、截图、清理;而 pytest-selenium 把这些封装成可配置的 fixture 和命令行参数。
但代价是灵活性下降:
- 无法直接访问
Options对象做深度定制(比如禁用图片加载、绕过证书验证)—— 必须通过--chrome-options命令行传参,且格式受限(如--chrome-options="--headless --disable-gpu") - 不支持自定义 driver 初始化逻辑(比如连接远程 Selenium Grid)—— 得重写
driverfixture 或用--driver-cls指定类,但文档稀少,易踩坑 - 多浏览器并行测试时,
--driver chrome --driver firefox不会同时跑,而是顺序执行两轮;真正并行需结合pytest-xdist+ 多个 pytest 调用,不是 pytest-selenium 原生能力
简单说:适合快速搭建标准 Web UI 回归流程;一旦需要精细控制 WebDriver 行为或集成复杂 CI 环境,很快就会绕过它,回到手写 fixture 的路子上。


















