跳转到内容

Playwright 自动化测试

安装 Python 后,安装 Playwright 与所需浏览器:

Terminal window
pip install playwright pytest pytest-playwright
playwright install chromium

需要覆盖多浏览器时,可将最后一条改为 playwright install。测试报告可按团队需要接入 Allure 等工具。

推荐在 conftest.py 统一管理浏览器、环境参数和登录态;测试用例只描述业务行为和断言。典型流程是:准备数据与登录 → 打开目标页面 → 执行操作 → 等待可观察结果 → 断言并在失败时保留截图、Trace 或网络日志。

def test_submit_form(page):
page.goto("https://example.test/form")
page.get_by_label("名称").fill("demo")
page.get_by_role("button", name="提交").click()
expect(page.get_by_text("提交成功")).to_be_visible()

定位优先使用 get_by_roleget_by_label 等面向用户语义的方式,减少对 CSS 结构和易变文案的依赖。录制脚本可作为探索页面的起点,但提交前应收敛为可读、稳定的页面对象或公共方法。