Playwright 定位器
系统核对 Playwright Locator 惰性查找与自动等待原理、getByRole 及 12 种 ARIA 角色与状态选项、文本/标签/占位符/图片/标题/TestId/CSS/XPath 定位及链式过滤组合。
学完这一章,你能够
- 系统核对 Playwright Locator 惰性查找与自动等待原理、getByRole 及 12 种 ARIA 角色与状态选项、文本/标签/占位符/图片/标题/TestId/CSS/XPath 定位及链式过滤组合。
什么是 Locator 及其惰性自动等待原理
Locator(定位器)是 Playwright 查找页面元素的核心抽象。与一次性查询 DOM 快照的 `document.querySelector()` 不同,创建 Locator 时只保存一条查找规则而不会立刻访问 DOM;直到真正执行 `.click()`、`.fill()` 或 `expect(locator)` 断言时,Playwright 才实时求值并自动等待与重试,直到元素出现且满足可操作条件或触发超时。本站离线 Chromium 实测验证:在按钮尚未注入 DOM 前创建 `page.get_by_role('button', name='提交')`(此时 `count()` 为 `0`),随后经 `100ms` 异步插入按钮并直接调用 `.click()`,无需任何手动等待即精准点击成功。
按角色定位:getByRole() 与 ARIA 语义
`getByRole()` 是 Playwright 最优先推荐的定位策略,它依据元素的无障碍角色(ARIA Role,如 `button`、`link`、`heading`、`textbox`、`checkbox`、`radio`、`combobox`、`img`、`list`、`listitem`、`navigation`、`table`)匹配元素,最贴近真实用户的交互感知且不脆弱于 CSS 类名重构。本站离线实测在同一自包含页面上一次验证全部 12 类 ARIA 角色,所有计数均与页面语义结构精确一致。
配合 `name` 选项可按可访问名称(来自元素文本、`aria-label` 或关联 `<label>`,支持字符串与正则)进一步收敛目标;配合 `checked`、`disabled`、`expanded`、`selected` 等状态选项还可精确筛选控件状态(如 `getByRole('checkbox', { name: '同意协议', checked: false })`)。本站实测覆盖 `aria-label` 按钮、正则链接匹配以及 `checked`/`disabled`/`expanded`/`selected` 状态过滤,全部精准命中单一目标。
文本、表单标签、占位符、图片与标题定位
`getByText()` 按元素文本内容定位,默认执行子字符串部分匹配,传入 `{ exact: true }` 时才要求与完整文本完全一致,亦支持正则表达式。本站离线实测页面同时存在“欢迎访问 蓝色天空”与“蓝色天空”两段文本时,`get_by_text('蓝色天空')` 匹配 `2` 项,而 `get_by_text('蓝色天空', exact=True)` 仅精确匹配 `1` 项。
针对表单输入控件,若存在 `for/id` 关联或包裹嵌套的 `<label>`,应优先使用 `getByLabel()`(同样支持 `{ exact: true }`);若控件没有 `<label>` 但具备 `placeholder`,再退而选用 `getByPlaceholder()`。总体优先级遵循 `getByRole()` → `getByLabel()` / `getByPlaceholder()` → `getByText()`,仅在缺乏语义化结构时再考虑测试 ID 或底层选择器。
针对带 `alt` 描述的 `<img>` 可用 `getByAltText()`(支持正则忽略大小写),针对带 `title` 提示属性的元素可用 `getByTitle()`。二者使用频率低于前述语义方法,适合图标按钮或纯图元素缺少其他可读名称的场景;本站离线实测均准确可见并命中目标。
TestId 兜底、CSS/XPath 与链式过滤组合
`getByTestId()` 默认通过 `data-testid` 属性定位,是语义定位不可行时的稳定兜底方案,既可命中单一按钮也可返回多条列表项。如果项目沿用 `data-cy` 等其他约定属性,可在 `playwright.config.ts` 中设置 `use: { testIdAttribute: 'data-cy' }`(Python 中可调用 `playwright.selectors.set_test_id_attribute('data-cy')`)。本站离线实测切换为 `data-cy` 后成功命中 `cy-save` 按钮文本 `保存`。
`page.locator()` 支持完整 CSS 选择器(类名、ID、属性、后代组合及 Playwright 扩展伪类 `:has-text(...)`)与 `xpath=...` 表达式。由于 CSS 易随样式调整失效而 XPath 可读性与维护性较差,二者仅作为最后备用方案;本站离线实测验证 `.submit-btn`、`[data-type="primary"]`、`button:has-text("保存")` 以及两类 XPath 均准确提取目标文本。
Locator 支持强大的链式缩小范围:`.first()`、`.last()`、`.nth(i)` 按序选取(索引从 `0` 开始);`.filter()` 支持 `hasText`、`hasNotText`、`has`(含子定位器)与 `hasNot` 四类过滤;在容器定位器上继续调用 `.locator()` 可限定子作用域(如对话框内的确认按钮);`.and()` 与 `.or()`(Python 中为 `.and_()`、`.or_()`,支持逻辑交并组合)可组合多重条件。本站离线实测 3 项待办列表与弹窗确认按钮:`first`、`nth(1)`、`last`、`has_not_text`(`2` 项)、`has`(`1` 项)、`has_not`(`2` 项)、多级嵌套 `dlg-ok` 以及 `and_`(`1` 项)/`or_`(`2` 项)全部一次精确通过。
下表总结常见 ARIA 角色、表单标签与占位符抉择,以及全部 8 级定位方式的推荐优先级。
getByRole() 常见 ARIA Role 对照表
| Role | 对应 HTML 元素 | 使用示例 |
|---|---|---|
| 'button' | <button>、role="button" | getByRole('button', { name: '登录' }) |
| 'link' | <a> | getByRole('link', { name: '了解更多' }) |
| 'heading' | <h1> ~ <h6> | getByRole('heading', { name: 'Playwright 教程' }) |
| 'textbox' | <input type="text">、<textarea> | getByRole('textbox', { name: '用户名' }) |
| 'checkbox' | <input type="checkbox"> | getByRole('checkbox', { name: '记住我' }) |
| 'radio' | <input type="radio"> | getByRole('radio', { name: '男' }) |
| 'combobox' | <select> | getByRole('combobox', { name: '城市' }) |
| 'img' | <img> | getByRole('img', { name: 'Logo' }) |
| 'list' | <ul>、<ol> | getByRole('list') |
| 'listitem' | <li> | getByRole('listitem') |
| 'navigation' | <nav> | getByRole('navigation') |
| 'table' | <table> | getByRole('table') |
getByLabel() 与 getByPlaceholder() 选择对比
| 方法 | 适用场景 | 优先级 |
|---|---|---|
| getByLabel() | 表单控件存在关联或嵌套 <label> 元素时 | 优先使用 |
| getByPlaceholder() | 表单控件无 <label> 但定义了 placeholder 属性时 | 次选 |
Playwright 定位方式推荐优先级总表
| 优先级 | 方法 | 使用条件 |
|---|---|---|
| 1(最推荐) | getByRole() | 元素具备明确的 ARIA 无障碍角色与名称 |
| 2 | getByLabel() | 表单控件有关联的 <label> |
| 3 | getByPlaceholder() | 输入框带有 placeholder 提示文本 |
| 4 | getByText() | 非交互或文本元素具有稳定可见文本 |
| 5 | getByAltText() | <img> 图片具备明确 alt 说明 |
| 6 | getByTitle() | 元素具备明确 title 属性 |
| 7(兜底) | getByTestId() | 语义定位不稳定或缺失时借助 data-testid |
| 8(最后选择) | locator() | 使用 CSS 选择器或 XPath 精确兜底 |
离线 Chromium 实测 12 类 ARIA 角色、语义定位、自定义 TestId 与链式过滤
"""Offline Playwright Chromium lab for Chapter 16: Playwright Locators."""
import json
import re
from playwright.sync_api import sync_playwright, expect
HTML_DOC = """<!doctype html>
<html><head><meta charset='utf-8'><title>Locators Lab</title></head>
<body>
<nav aria-label="主导航"><a href="#home">首页</a><a href="#more">了解更多</a></nav>
<main>
<h1>欢迎使用 Playwright 教程</h1>
<img src="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' width='20' height='20'></svg>" alt="Site Logo" width="20" height="20" />
<div id="delayed-host"></div>
<label for="username">用户名</label>
<input id="username" type="text" />
<label>密码 <input id="password" type="password" /></label>
<input placeholder="请输入搜索关键词" />
<textarea placeholder="说说你的想法..."></textarea>
<label><input type="checkbox" checked /> 记住我</label>
<label><input type="checkbox" /> 同意协议</label>
<label><input type="radio" name="gender" value="m" checked /> 男</label>
<label for="city">城市</label>
<select id="city">
<option value="bj" selected>北京</option>
<option value="sh">上海</option>
</select>
<button id="btn-login" class="submit-btn primary" data-type="primary" type="submit" data-testid="submit-btn">登录</button>
<button aria-label="关闭对话框" title="关闭当前页面">X</button>
<button disabled>禁用按钮</button>
<button aria-expanded="true">展开菜单</button>
<button data-cy="cy-save">保存</button>
<p id="p-welcome">欢迎访问 蓝色天空</p>
<p id="p-exact">蓝色天空</p>
<ul data-testid="todo-list">
<li data-testid="todo-item">任务一 <button class="delete">删除</button></li>
<li data-testid="todo-item">任务二 <span data-testid="badge">VIP</span></li>
<li data-testid="todo-item">已删除任务</li>
</ul>
<div role="dialog" aria-label="确认框">
<div class="content"><button id="dlg-ok">确认</button></div>
</div>
<table><tr><td>单元格1</td></tr></table>
</main>
<script>
window.__clicked = [];
document.addEventListener('click', e => {
if (e.target.id) window.__clicked.push(e.target.id);
});
window.__spawnLateButton = () => setTimeout(() => {
const b = document.createElement('button');
b.id = 'late-submit';
b.textContent = '提交';
document.getElementById('delayed-host').appendChild(b);
}, 100);
</script>
</body></html>
"""
def launch_browser(p):
for kwargs in (dict(channel="chrome", headless=True), dict(channel="msedge", headless=True), dict(headless=True)):
try:
return p.chromium.launch(**kwargs)
except Exception:
continue
raise RuntimeError("No local Chromium executable found")
def main():
cases = []
with sync_playwright() as p:
browser = launch_browser(p)
ctx = browser.new_context()
page = ctx.new_page()
page.set_content(HTML_DOC)
# Case 1: Lazy locator auto-waiting for async DOM button
late_btn = page.get_by_role("button", name="提交")
existed_immediately = late_btn.count()
page.evaluate("() => window.__spawnLateButton()")
late_btn.click()
clicked_ids = page.evaluate("() => window.__clicked")
actual1 = {"existed_immediately": existed_immediately, "clicked_late": "late-submit" in clicked_ids}
expected1 = {"existed_immediately": 0, "clicked_late": True}
cases.append(dict(name="lazy_locator_auto_wait", expected=expected1, actual=actual1, passed=actual1 == expected1))
# Case 2: All 12 ARIA roles + name (text / aria-label / regex) + state options
role_checks = {
"button": page.get_by_role("button", name="登录").count(),
"link": page.get_by_role("link", name=re.compile("了解|首页")).count(),
"heading": page.get_by_role("heading", name="欢迎使用 Playwright 教程").count(),
"textbox": page.get_by_role("textbox", name="用户名").count(),
"checkbox_checked": page.get_by_role("checkbox", checked=True).count(),
"checkbox_unchecked_named": page.get_by_role("checkbox", name="同意协议", checked=False).count(),
"radio": page.get_by_role("radio", name="男").count(),
"combobox": page.get_by_role("combobox", name="城市").count(),
"option_selected": page.get_by_role("option", selected=True).count(),
"img": page.get_by_role("img", name="Site Logo").count(),
"list": page.get_by_role("list").count(),
"listitem": page.get_by_role("listitem").count(),
"navigation": page.get_by_role("navigation").count(),
"table": page.get_by_role("table").count(),
"aria_label_btn": page.get_by_role("button", name="关闭对话框").count(),
"disabled_btn": page.get_by_role("button", disabled=True).count(),
"expanded_btn": page.get_by_role("button", expanded=True).count(),
}
expected2 = {
"button": 1, "link": 2, "heading": 1, "textbox": 1,
"checkbox_checked": 1, "checkbox_unchecked_named": 1,
"radio": 1, "combobox": 1, "option_selected": 1,
"img": 1, "list": 1, "listitem": 3, "navigation": 1, "table": 1,
"aria_label_btn": 1, "disabled_btn": 1, "expanded_btn": 1,
}
cases.append(dict(name="get_by_role_all_roles_and_states", expected=expected2, actual=role_checks, passed=role_checks == expected2))
# Case 3: get_by_text (partial vs exact vs regex), get_by_label, get_by_placeholder, get_by_alt_text, get_by_title
partial_cnt = page.get_by_text("蓝色天空").count()
exact_cnt = page.get_by_text("蓝色天空", exact=True).count()
regex_cnt = page.get_by_text(re.compile("欢迎访问|蓝色天空")).count()
page.get_by_label("用户名", exact=True).fill("pw_user")
page.get_by_label("密码").fill("secret123")
page.get_by_placeholder("请输入搜索关键词").fill("Playwright")
page.get_by_placeholder("说说你的想法...").fill("结构清晰")
expect(page.get_by_alt_text("Site Logo")).to_be_visible()
expect(page.get_by_alt_text(re.compile("logo", re.I))).to_be_visible()
title_text = page.get_by_title("关闭当前页面").text_content()
actual3 = {
"partial_cnt": partial_cnt,
"exact_cnt": exact_cnt,
"regex_cnt": regex_cnt,
"username_val": page.locator("#username").input_value(),
"password_val": page.locator("#password").input_value(),
"search_val": page.get_by_placeholder("请输入搜索关键词").input_value(),
"title_btn_text": title_text,
}
expected3 = {
"partial_cnt": 2,
"exact_cnt": 1,
"regex_cnt": 2,
"username_val": "pw_user",
"password_val": "secret123",
"search_val": "Playwright",
"title_btn_text": "X",
}
cases.append(dict(name="text_label_placeholder_alt_title", expected=expected3, actual=actual3, passed=actual3 == expected3))
# Case 4: get_by_test_id + custom test_id attribute + CSS + XPath
expect(page.get_by_test_id("todo-item")).to_have_count(3)
default_tid_text = page.get_by_test_id("submit-btn").text_content()
p.selectors.set_test_id_attribute("data-cy")
custom_cy_text = page.get_by_test_id("cy-save").text_content()
p.selectors.set_test_id_attribute("data-testid")
css_cls = page.locator(".submit-btn").text_content()
css_attr = page.locator('[data-type="primary"]').text_content()
css_has_text = page.locator('button:has-text("保存")').text_content()
xpath_btn = page.locator('xpath=//button[@type="submit"]').text_content()
xpath_h1 = page.locator('xpath=//h1[contains(text(), "Playwright")]').text_content()
actual4 = {
"default_tid": default_tid_text,
"custom_cy": custom_cy_text,
"css_cls": css_cls,
"css_attr": css_attr,
"css_has_text": css_has_text,
"xpath_btn": xpath_btn,
"xpath_h1": xpath_h1,
}
expected4 = {
"default_tid": "登录",
"custom_cy": "保存",
"css_cls": "登录",
"css_attr": "登录",
"css_has_text": "保存",
"xpath_btn": "登录",
"xpath_h1": "欢迎使用 Playwright 教程",
}
cases.append(dict(name="testid_custom_attr_css_and_xpath", expected=expected4, actual=actual4, passed=actual4 == expected4))
# Case 5: Chaining (.first, .last, .nth, .filter, nested .locator, .and_, .or_)
items = page.get_by_role("listitem")
first_txt = items.first.text_content().strip()
second_txt = items.nth(1).text_content().strip()
last_txt = items.last.text_content().strip()
not_deleted_cnt = items.filter(has_not_text="已删除").count()
has_btn_cnt = items.filter(has=page.get_by_role("button")).count()
has_not_badge_cnt = items.filter(has_not=page.get_by_test_id("badge")).count()
nested_del_text = page.get_by_test_id("todo-list").locator("button.delete").text_content()
dlg_ok_id = (
page.get_by_role("dialog")
.locator("div.content")
.locator("button")
.filter(has_text="确认")
.get_attribute("id")
)
and_cnt = page.get_by_role("button").and_(page.get_by_text("提交")).count()
or_cnt = page.get_by_text("蓝色天空", exact=True).or_(page.get_by_title("关闭当前页面")).count()
actual5 = {
"first": first_txt,
"second": second_txt,
"last": last_txt,
"not_deleted_cnt": not_deleted_cnt,
"has_btn_cnt": has_btn_cnt,
"has_not_badge_cnt": has_not_badge_cnt,
"nested_del": nested_del_text,
"dlg_ok_id": dlg_ok_id,
"and_cnt": and_cnt,
"or_cnt": or_cnt,
}
expected5 = {
"first": "任务一 删除",
"second": "任务二 VIP",
"last": "已删除任务",
"not_deleted_cnt": 2,
"has_btn_cnt": 1,
"has_not_badge_cnt": 2,
"nested_del": "删除",
"dlg_ok_id": "dlg-ok",
"and_cnt": 1,
"or_cnt": 2,
}
cases.append(dict(name="locator_chaining_filter_and_or", expected=expected5, actual=actual5, passed=actual5 == expected5))
ctx.close()
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
- 核对异步按钮惰性自动等待、12 种 ARIA Role 与状态选项、文本精确与子串匹配、data-cy 自定义测试属性、CSS/XPath 以及 first/nth/last/filter/and/or 链式筛选。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:33d1dbd73a6ed00626f40c3c709490b160b85d7cc503455cd412bff1d567683a
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:f4250894356b8b8a04204d99bf7c123877008892b515caff5490cf38376f42dc
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么在动态前端页面中,Playwright 强调复用 `Locator` 而不是提前用 `elementHandle` 或 `document.querySelector()` 缓存 DOM 节点?
展开参考解答
`Locator` 保存的是查找规则,每次操作或断言时都会重新解析 DOM 并自动等待可操作状态,即使组件重渲染替换了旧节点也能稳定命中;而缓存旧 DOM 句柄在重渲染后会立即失效报 stale/detached 错误。