附录 A 命令速查表
# 环境
py -m venv .venv
.\.venv\Scripts\Activate.ps1
pip install -r requirements.txt
# 浏览器
python -m playwright install chromium
python -m playwright install --with-deps chromium
# 录制
playwright codegen https://example.com
playwright codegen --target python -o demo.py https://example.com
# 运行
pytest -v
pytest -k login
pytest -m smoke
pytest --headed --slowmo 500
pytest --browser firefox
pytest --device "iPhone 13"
pytest -n auto
pytest --tracing retain-on-failure
pytest --html=report.html --self-contained-html
# 回放
playwright show-trace test-results\<case>\trace.zip
附录 B 定位器与断言速查
| 需求 |
写法 |
| 按角色 + 名称 |
page.get_by_role("button", name="登录") |
| 按 label |
page.get_by_label("用户名") |
| 按占位符 |
page.get_by_placeholder("搜索") |
| 按文本 |
page.get_by_text("欢迎") |
| 按 testid |
page.get_by_test_id("submit") |
| 区域内查找 |
page.get_by_role("dialog").get_by_role("button") |
| 按条件过滤 |
page.locator("li").filter(has_text="张三") |
| 第 N 个 |
page.get_by_role("row").nth(2) |
| 正则 |
page.get_by_role("heading", name=re.compile(r"订单\d+")) |
| 可见 |
expect(loc).to_be_visible() |
| 文本 |
expect(loc).to_have_text("已支付") |
| 数量 |
expect(loc).to_have_count(3) |
| 输入值 |
expect(loc).to_have_value("99.5") |
| URL |
expect(page).to_have_url(re.compile(r"/dashboard")) |
附录 C 学习资源
| 资源 |
链接 |
| Playwright Python 官方文档 |
https://playwright.dev/python/docs/intro |
| 测试运行器(pytest 集成) |
https://playwright.dev/python/docs/test-runners |
| 定位器指南 |
https://playwright.dev/python/docs/locators |
| 断言 API |
https://playwright.dev/python/docs/api/class-locatorassertions |
| 中文站 |
https://playwright.cn/ |
| pytest 官方文档 |
https://docs.pytest.org/ |
| pytest-playwright |
https://pypi.org/project/pytest-playwright/ |
最后一句:三天只能让你“会写”。真正让你变强的,是接下来在真实项目里写下的每一条用例、以及每一次失败的排查。