Playwright 页面自动化测试入门

本文用一个本地 HTML 页面演示浏览器自动化的基本流程:打开页面、填写输入框、点击按钮并检查结果。自动化测试只应用于自己编写、拥有或明确获准测试的页面;不要用它绕过付费访问、登录限制或网站的访问规则。

1. 安装环境

先安装 Python,然后在终端运行:

1
2
python -m pip install playwright
python -m playwright install chromium

Playwright 会安装对应的浏览器运行文件。若安装失败,可查看官方安装说明,并确认当前 Python 环境与终端使用的是同一个环境。

2. 准备一个本地测试页面

下面的页面通过 set_content 加载到浏览器中,不会访问第三方网站:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from playwright.sync_api import sync_playwright

html = """
<!doctype html>
<html lang="zh-CN">
<meta charset="utf-8">
<title>本地测试页</title>
<label>姓名 <input id="name"></label>
<button id="submit" onclick="document.querySelector('#result').textContent =
'你好,' + document.querySelector('#name').value">提交</button>
<p id="result"></p>
</html>
"""

with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
page.set_content(html)

page.locator("#name").fill("小明")
page.locator("#submit").click()
result = page.locator("#result").text_content()

assert result == "你好,小明"
print(result)
browser.close()

运行后,程序会在无界面浏览器中填写表单、点击按钮并检查页面结果。locator 用来定位页面元素,fill 填写输入框,click 触发点击,assert 验证测试结果。

3. 改为测试自己的本地网站

如果你正在开发一个本地网站,可以先按项目说明启动开发服务器,再把 page.set_content(html) 换成:

1
page.goto("http://127.0.0.1:8000")

选择器应来自自己页面上的稳定属性,例如 id、可访问性角色或专门的测试属性。测试结束后关闭浏览器;如果需要看到操作过程,可把 headless=True 改为 False。

4. 让测试更稳定

  • 用清楚的断言验证结果,不要只检查脚本没有报错。
  • 等待元素达到预期状态,再继续操作;避免固定写很长的 sleep。
  • 每个测试准备独立数据,避免依赖上一次运行留下的状态。
  • 不要在脚本或日志中保存真实账号密码、Cookie 或个人数据。
  • 只在获准的测试环境中运行,控制请求频率,不要对不属于自己的服务做压力测试。

Playwright 还有官方的定位器、等待和测试框架等功能,进一步使用时请查看官方文档。