Playwright 自动化测试框架入门与核心操作指南
与 Selenium 相比,Playwright 采用自包含架构,无需额外搭配测试框架即可独立完成 Web 自动化任务。其调用链路为:Playwright 库 → Playwright Driver → 浏览器驱动,相较 Selenium 的多层依赖更为简洁。
环境搭建
通过 pip 安装
pip install playwright
# 使用国内镜像加速
pip install playwright -i https://pypi.tuna.tsinghua.edu.cn/simple
安装完成后,Playwright 的可执行文件位于 Python 安装目录下的 Scripts 文件夹中。
浏览器部署
Playwright 内置了 Chromium、Firefox 等浏览器支持。执行以下命令完成浏览器下载:
# 安装全部浏览器
playwright install
# 仅安装指定浏览器
playwright install chromium
IDE 集成配置
VS Code 环境
确保已安装 Python 与 Playwright 后,在扩展商店中搜索并安装 Microsoft 官方认证的 Python 与 Playwright 插件,即可获得完整的语法支持。
PyCharm 环境
选择 Python 3.7+ 的解释器,在终端执行:
pip install pytest-playwright
随后将测试运行器默认配置修改为 pytest,即可运行符合 pytest 规范的测试用例。
核心 API 详解
官方文档地址:https://playwright.dev/
自定义浏览器实例
browser = p.chromium.launch(
headless=False,
executable_path='C:/Program Files/Google/Chrome/Application/chrome.exe'
)
超时控制
默认超时时间为 30 秒,可按需调整:
# 单次操作设置 10 毫秒超时
element.inner_text(timeout=10)
# 修改上下文级别的默认超时
ctx = browser.new_context()
ctx.set_default_timeout(50)
元素定位策略
CSS 选择器定位
Class 多值匹配
<span class="chinese student">张三</span>
# 匹配任一 class 值
page.locator(".chinese")
page.locator(".student")
# 错误写法:空格会被解析为后代选择器
# page.locator(".chinese student") ❌
# 正确:同时包含多个 class
page.locator(".chinese.student")
属性选择器
# 精确匹配属性值
page.locator('[href="http://news.baidu.com"]')
# 标签 + 属性联合约束
page.locator('a[href="http://news.baidu.com"]')
# 仅判断属性存在
page.locator('[href]')
# 属性值包含指定字符串
page.locator('[href*="news."]')
# 属性值前缀匹配
page.locator('[href^="http://news"]')
# 属性值后缀匹配
page.locator('[href$="news.baidu.com"]')
# 多属性组合条件
page.locator('[href*="news"][target="_blank"]')
层级关系选择
| 关系类型 | 语法示例 |
|---|---|
| 直接子元素 | 父 > 子 或 父 > 子 > 孙 |
| 后代元素 | 祖先 后代 或 祖先 后代 后代 |
伪类选择器
# 第 n 个子元素(限定 span 标签)
page.locator('span:nth-child(2)')
# 不限定标签的第 n 个子元素
page.locator(':nth-child(2)')
# 倒数第 n 个子元素
page.locator('span:nth-last-child(2)')
# 第 n 个同类型子元素
page.locator('span:nth-of-type(2)')
page.locator('span:nth-last-of-type(2)')
# 偶数/奇数索引节点
page.locator('p:nth-child(even)')
page.locator('p:nth-child(odd)')
page.locator(':nth-of-type(even)')
兄弟元素与父元素
CSS 方式
# 相邻后继兄弟
page.locator('[href="http://map.baidu.com"] + [href]')
# 所有后继兄弟
page.locator('[href="http://map.baidu.com"] ~ *')
# 带属性的后继兄弟
page.locator('[href="http://map.baidu.com"] ~ [href]')
XPath 方式
# 所有后续兄弟节点
page.locator('//*[@href="http://map.baidu.com"]/following-sibling::*')
# 带 href 属性的后续兄弟
page.locator('//*[@href="http://map.baidu.com"]/following-sibling::*[@href]')
# 限定标签的后续兄弟
page.locator('//*[@href="http://map.baidu.com"]/following-sibling::a')
# 前置兄弟节点
page.locator('//*[@href="http://map.baidu.com"]/preceding-sibling::a')
# 父节点(向上回溯)
page.locator('//*[@href="http://map.baidu.com"]/..')
page.locator('//*[@href="http://map.baidu.com"]/../..')
语义化定位
文本内容定位
import re
# 包含指定文本
page.get_by_text("新闻")
# 正则匹配
results = page.get_by_text(re.compile("闻$")).all()
ARIA 角色定位
Playwright 支持基于 WAI-ARIA 规范的 role 属性进行元素识别,便于构建无障碍友好的自动化测试:
<div class="alert-message" role="alert">操作成功</div>
page.get_by_role("alert")