Playwright 是一款由微软开发的开源自动化测试和浏览器自动化工具,主要用于 Web 应用的端到端测试、UI 自动化和网页抓取等场景。它支持多种现代浏览器(如 Chromium、Firefox 和 WebKit),并提供了简洁、高效的 API,让开发者能够轻松实现跨浏览器的自动化操作。
在 Playwright 中, getByRole 是用于查找页面上具有特定语义角色(Role)的元素的一种方式,这个语义角色是基于ARIA(Accessible Rich Internet Applications)规范 中的定义。
一、getByRole 的作用
Playwright 提供了 getByRole(role[, options])方法,它基于可访问性树(Accessibility Tree)来查找元素,而不是仅仅靠标签、类名或 ID。
csharp
await page.getByRole("button", { name: "提交" }).click();
这段代码会查找"语义角色是 button,且可访问名称为'提交'"的按钮",然后点击它。
二、什么是 Role?
Role 是只元素在页面中"语义作用"或"功能",常见的角色包括:
Role 名称 | 对应 HTML 元素 | 示例 |
---|---|---|
button |
<button> , <input type="submit"> |
按钮 |
link |
<a href="..."> |
超链接 |
textbox |
<input type="text"> , <textarea> |
文本输入框 |
checkbox |
<input type="checkbox"> |
复选框 |
heading |
<h1> ~ <h6> |
标题 |
img |
<img> |
图片 |
list |
<ul> , <ol> |
列表 |
listitem |
<li> |
列表项 |
Playwright 会自动从 HTML 标签推断元素的角色。
三、在 HTML 中如何识别元素的 Role?
方法 1: 通过标签推断(隐式角色)
- •
<button>
-> role="button" - •
<a href="...">
-> role="link" - •
<input type="checkbox">
-> role="checkbox"
这些 HTML 标签天生就有语义角色,Playwright 会识别。
方法 2:使用 role 属性(显示角色)
你可以手动给元素增加 role,来赋予特定语义:
css
<div role="button">我是一个自定义按钮</div>
Playwright 的 getByRole('button')
就能识别它。
四、调试技巧:查看 Role
1. 使用浏览器开发者工具
Chrome 或 Edge:
- • 打开 DevTools → Inspect 元素 → 在 "Accessibility" 面板中查看 Role。
2. 使用 Playwright 的 CLI 工具
arduino
npx playwright codegen https://example.com
它会自动生成包含 getByRole 的代码,可以参考 role 是如何被识别的。
五、总结
名称 | 含义 |
---|---|
role |
元素的语义功能,例如 button , link , textbox 等 |
getByRole |
基于语义角色查找页面元素,更稳定、易维护 |
识别方式 | 默认标签语义或手动设置 role="..." |
如果你构建的页面具有良好的语义化结构,那么 getByRole
会非常好用,而且自动适配无障碍和测试要求。
.preview-wrapper pre::before { position: absolute; top: 0; right: 0; color: #ccc; text-align: center; font-size: 0.8em; padding: 5px 10px 0; line-height: 15px; height: 15px; font-weight: 600; } .hljs.code__pre > .mac-sign { display: flex; } .code__pre { padding: 0 !important; } .hljs.code__pre code { display: -webkit-box; padding: 0.5em 1em 1em; overflow-x: auto; text-indent: 0; } h2 strong { color: inherit !important; }
本文使用 文章同步助手 同步