当前位置:首页 > 技术 > 正文内容

Playwright 自动化测试框架入门与核心操作指南

访客 技术 2026年7月19日 4

与 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")

相关文章

Linux crontab 详解

1) crontab 是什么cron 是 Linux 的定时任务守护进程;crontab 是用来编辑/查看“按时间周期执行命令”的表(cron table)。常见两类:用户 crontab:每个用户一份(crontab -e 编辑)系统级 crontab / cron.d:可指定执行用户(/etc/crontab、/etc/cron.d/*)2) crontab 时间...

富文本里可以允许的 HTML 属性

一、所有标签默认允许的安全属性(极少)class        (可选)id           (通常建议禁用)title️ 注意:id 容易被滥用做锚点注入,很多系统直接禁用class 允许的话最好只允许固定前缀(如 editor-*)二、a 标签允许属性<a href="" t...

Mac 安装 Node.js 指南

方法一:通过官网安装包(最简单,适合初学者)如果你只是想快速安装并开始使用,这是最直接的方法。访问 Node.js 官网。页面会显示两个版本:LTS (Recommended For Most Users):长期支持版,最稳定。建议选这个。Current:最新特性版,包含最新功能但可能不够稳定。下载 .pkg 安装包并运行。按照安装向导点击“下一步”即可完成。方法二:使用 Homebrew 安装(...

Dom\HTML_NO_DEFAULT_NS 的副作用:自动加闭合标签

在使用Dom\HTMLDocument时,Dom\HTML_NO_DEFAULT_NS 将禁止在解析过程中设置元素的命名空间, 此设置是为了与DOMDocument向后兼容而存在的。当使用它时,已知的一个副作用就是:自动加闭合标签例如 </img> 为什么会这样?当你使用:Dom\HTML_NO_DEFAULT_NS文档会变成 无命名空间模式,此时内部更接近 XML...

Laravel 事件和监听器创建

在 Laravel 中,使用 Artisan 命令创建 Events(事件) 和 Listeners(监听器) 是非常高效的。你可以通过以下几种方式来实现:1. 手动创建单个 Event如果你只想创建一个事件类,可以使用 make:event 命令:Bashphp artisan make:event UserRegistered执行后,文件将生成在 app/Even...

自定义域名解析神器 dnsmasq

什么是 dnsmasq?dnsmasq 是一个轻量级、功能强大的网络服务工具,专为小型和中等规模网络设计。它是一个综合的网络基础设施解决方案[1]。dnsmasq 能做什么?功能说明应用场景DNS 转发与缓存将 DNS 查询转发到上游服务器(ISP、Google DNS 等),并在本地缓存结果加快 DNS 查询速度,减少外部 DNS 流量本地 DNS解析本地网络设备的主机名,无需编辑&n...

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。