必须用pytest-playwright插件,不能只装pytest和playwright;否则page参数报fixture未找到错误,因该插件注册page等fixture并统一管理生命周期、多浏览器支持及调试功能。

直接结论:必须用 pytest-playwright 插件,不能只装 pytest 和 playwright 两个包。 否则你写不出能自动注入浏览器实例的测试函数,page 或 browser 参数会报 fixture 'page' not found 错误。
为什么不能手动调用 sync_playwright()
新手常犯的错误是照搬 Playwright 官方文档的写法,在每个测试里自己写 with sync_playwright() as p:。这会导致:
- 每次测试都重新启动浏览器进程,速度极慢(尤其多用例时)
- 无法复用
page、browser、context等 fixture 的生命周期控制(比如想让整个测试模块共用一个 browser) - 视频录制、截图、tracing 等调试能力全部失效——因为这些功能依赖
pytest-playwright在 fixture 层统一接管启动逻辑 - 多浏览器并行(
--browser chromium --browser firefox)根本跑不起来
必须安装的三个包及其分工
缺一不可,顺序也重要:
-
playwright:提供底层 API(如Page,Browser类),但不包含 pytest 集成逻辑 -
pytest:测试运行器,负责发现test_*.py文件和def test_*函数 -
pytest-playwright:关键桥梁。它注册了page、browser、context、playwright等 fixture,并在命令行参数(如--browser)和配置文件中做解析
安装命令必须是:pip install pytest playwright pytest-playwright,然后单独执行 playwright install 下载浏览器二进制文件。
测试函数签名必须匹配 fixture 名称
你写的测试函数参数名不是随便起的,它必须和 pytest-playwright 提供的 fixture 名完全一致。常见合法组合:
-
def test_something(page: Page):→ 自动获得一个干净、隔离的Page实例(推荐,最常用) -
def test_something(browser: Browser):→ 获得浏览器实例,可手动new_context()(适合需要精细控制 context 的场景) -
def test_something(context: BrowserContext):→ 获得上下文,可用于模拟多标签页、权限设置等
错误写法:def test_something(p: Page): 或 def test_something(my_page: Page): —— 这会导致 pytest 找不到对应 fixture,直接报错。
容易被忽略的 CLI 参数生效前提
--headed、--slowmo、--video on 这些参数看似简单,但它们只在 pytest-playwright 的 fixture 初始化阶段起作用。如果没装这个插件,加了也白加。
更隐蔽的问题是:这些参数默认只对 page fixture 生效。如果你用了 browser fixture 并自己调 browser.new_page(),--slowmo 就不会减速你的操作——因为减速逻辑实现在 page fixture 的封装层里。
所以,除非有强定制需求,否则坚持用 page 参数,别绕过它自己 new page。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!











