其他定位器
简介
查看主要定位器指南,了解最常用和推荐的定位器。
除了推荐的定位器(例如 page.get_by_role() 和 page.get_by_text())之外,Playwright 还支持本指南中描述的各种其他定位器。
CSS 定位器
我们建议优先使用用户可见的定位器,例如文本或可访问角色,而不是使用与实现绑定且在页面更改时可能失效的 CSS 定位器。
Playwright 可以通过 CSS 选择器定位元素。
- 同步
- 异步
page.locator("css=button").click()
await page.locator("css=button").click()
Playwright 在两个方面增强了标准 CSS 选择器
- CSS 选择器可以穿透开放的 Shadow DOM。
- Playwright 添加了自定义伪类,例如
:visible
、:has-text()
、:has()
、:is()
、:nth-match()
等。
CSS:按文本匹配
Playwright 包含多个 CSS 伪类,用于按文本内容匹配元素。
-
article:has-text("Playwright")
-:has-text()
匹配任何包含指定文本的元素,该文本可能位于元素内部的某个位置,例如子元素或后代元素中。匹配不区分大小写,会修剪空白并搜索子字符串。例如,
article:has-text("Playwright")
匹配<article><div>Playwright</div></article>
。请注意,
:has-text()
应与其他 CSS 特指符一起使用,否则它将匹配所有包含指定文本的元素,包括<body>
。- 同步
- 异步
# Wrong, will match many elements including <body>
page.locator(':has-text("Playwright")').click()
# Correct, only matches the <article> element
page.locator('article:has-text("All products")').click()# Wrong, will match many elements including <body>
await page.locator(':has-text("Playwright")').click()
# Correct, only matches the <article> element
await page.locator('article:has-text("Playwright")').click() -
#nav-bar :text("Home")
-:text()
伪类匹配包含指定文本的最小元素。匹配不区分大小写,会修剪空白并搜索子字符串。例如,这将查找
#nav-bar
元素内部包含文本“Home”的元素- 同步
- 异步
page.locator("#nav-bar :text('Home')").click()
await page.locator("#nav-bar :text('Home')").click()
-
#nav-bar :text-is("Home")
-:text-is()
伪类匹配文本完全相同的最小元素。精确匹配区分大小写,会修剪空白并搜索完整字符串。例如,
:text-is("Log")
不匹配<button>Log in</button>
,因为<button>
包含一个文本节点“Log in”,它不等于“Log”。但是,:text-is("Log")
匹配<button> Log <span>in</span></button>
,因为<button>
包含一个文本节点“ Log ”。类似地,
:text-is("Download")
不匹配<button>download</button>
,因为它区分大小写。
-
#nav-bar :text-matches("reg?ex", "i")
-:text-matches()
伪类匹配文本内容与类似 JavaScript 的正则表达式匹配的最小元素。例如,
:text-matches("Log\s*in", "i")
匹配<button>Login</button>
和<button>log IN</button>
。
文本匹配总是会规范化空白字符。例如,它会将多个空格变成一个,将换行符变成空格,并忽略开头和结尾的空白字符。
类型为 button
和 submit
的输入元素是根据其 value
进行匹配,而不是文本内容。例如,:text("Log in")
匹配 <input type=button value="Log in">
。
CSS:仅匹配可见元素
Playwright 在 CSS 选择器中支持 :visible
伪类。例如,css=button
匹配页面上的所有按钮,而 css=button:visible
仅匹配可见按钮。这对于区分非常相似但可见性不同的元素很有用。
考虑一个页面有两个按钮,第一个不可见,第二个可见。
<button style='display: none'>Invisible</button>
<button>Visible</button>
-
这将找到两个按钮并抛出严格性违规错误
- 同步
- 异步
page.locator("button").click()
await page.locator("button").click()
-
这只会找到第二个按钮,因为它可见,然后点击它。
- 同步
- 异步
page.locator("button:visible").click()
await page.locator("button:visible").click()
CSS:包含其他元素的元素
:has()
伪类是一个实验性 CSS 伪类。如果作为参数传递的任何选择器相对于给定元素的 :scope
匹配至少一个元素,则它会返回该元素。
以下代码片段返回包含 <div class=promo>
的 <article>
元素的文本内容。
- 同步
- 异步
page.locator("article:has(div.promo)").text_content()
await page.locator("article:has(div.promo)").text_content()
CSS:匹配其中一个条件的元素
逗号分隔的 CSS 选择器列表将匹配该列表中任一选择器可以选中的所有元素。
- 同步
- 异步
# Clicks a <button> that has either a "Log in" or "Sign in" text.
page.locator('button:has-text("Log in"), button:has-text("Sign in")').click()
# Clicks a <button> that has either a "Log in" or "Sign in" text.
await page.locator('button:has-text("Log in"), button:has-text("Sign in")').click()
:is()
伪类是一个实验性 CSS 伪类,可能有助于指定元素的额外条件列表。
CSS:基于布局匹配元素
基于布局的匹配可能会产生意外结果。例如,当布局改变一个像素时,可能会匹配到不同的元素。
有时,当目标元素缺少明显的特征时,很难找到一个好的选择器。在这种情况下,使用 Playwright 布局 CSS 伪类可能会有所帮助。可以将这些伪类与常规 CSS 结合使用,以精确定位多个选项中的一个。
例如,input:right-of(:text("Password"))
匹配位于文本“Password”右侧的输入字段 - 当页面有多个难以区分的输入时很有用。
请注意,布局伪类除了其他选择器(例如 input
)外使用时才有用。如果单独使用布局伪类,例如 :right-of(:text("Password"))
,很可能您找不到想要的输入,而会找到文本和目标输入之间的一些空元素。
布局伪类使用边界客户端矩形来计算元素的距离和相对位置。
:right-of(div > button)
- 匹配位于内部选择器匹配的任何元素右侧且在任何垂直位置的元素。:left-of(div > button)
- 匹配位于内部选择器匹配的任何元素左侧且在任何垂直位置的元素。:above(div > button)
- 匹配位于内部选择器匹配的任何元素上方且在任何水平位置的元素。:below(div > button)
- 匹配位于内部选择器匹配的任何元素下方且在任何水平位置的元素。:near(div > button)
- 匹配靠近(在 50 CSS 像素范围内)内部选择器匹配的任何元素的元素。
请注意,匹配结果按其与锚点元素的距离排序,因此您可以使用 locator.first 来选取最近的一个。这仅在您有一系列类似元素,其中最近的显然是正确的元素时有用。但是,在其他情况下使用 locator.first 很可能无法按预期工作 - 它不会定位您正在搜索的元素,而是定位碰巧最近的其他元素,例如随机的空 <div>
,或者已滚动出视口且当前不可见的元素。
- 同步
- 异步
# Fill an input to the right of "Username".
page.locator("input:right-of(:text(\"Username\"))").fill("value")
# Click a button near the promo card.
page.locator("button:near(.promo-card)").click()
# Click the radio input in the list closest to the "Label 3".
page.locator("[type=radio]:left-of(:text(\"Label 3\"))").first.click()
# Fill an input to the right of "Username".
await page.locator("input:right-of(:text(\"Username\"))").fill("value")
# Click a button near the promo card.
await page.locator("button:near(.promo-card)").click()
# Click the radio input in the list closest to the "Label 3".
await page.locator("[type=radio]:left-of(:text(\"Label 3\"))").first.click()
所有布局伪类都支持可选的最大像素距离作为最后一个参数。例如 button:near(:text("Username"), 120)
匹配与文本“Username”元素距离不超过 120 CSS 像素的按钮。
CSS:从查询结果中选取第 n 个匹配项
通常可以通过某些属性或文本内容来区分元素,这对于页面更改具有更好的弹性。
有时页面包含许多相似的元素,很难选择特定的一个。例如
<section> <button>Buy</button> </section>
<article><div> <button>Buy</button> </div></article>
<div><div> <button>Buy</button> </div></div>
在这种情况下,:nth-match(:text("Buy"), 3)
将从上面的代码片段中选择第三个按钮。请注意,索引是基于一的。
- 同步
- 异步
# Click the third "Buy" button
page.locator(":nth-match(:text('Buy'), 3)").click()
# Click the third "Buy" button
await page.locator(":nth-match(:text('Buy'), 3)").click()
:nth-match()
也可用于使用 locator.wait_for() 等待指定数量的元素出现。
- 同步
- 异步
# Wait until all three buttons are visible
page.locator(":nth-match(:text('Buy'), 3)").wait_for()
# Wait until all three buttons are visible
await page.locator(":nth-match(:text('Buy'), 3)").wait_for()
与:nth-child()
不同,元素不必是兄弟元素,它们可以位于页面上的任何位置。在上面的代码片段中,所有三个按钮都匹配 :text("Buy")
选择器,并且 :nth-match()
选择第三个按钮。
第 N 个元素定位器
您可以使用 nth=
定位器,传递一个基于零的索引,将查询范围缩小到第 n 个匹配项。
- 同步
- 异步
# Click first button
page.locator("button").locator("nth=0").click()
# Click last button
page.locator("button").locator("nth=-1").click()
# Click first button
await page.locator("button").locator("nth=0").click()
# Click last button
await page.locator("button").locator("nth=-1").click()
父元素定位器
当您需要定位某个元素的父元素时,大多数情况下应该使用 locator.filter() 根据子定位器进行过滤。例如,考虑以下 DOM 结构
<li><label>Hello</label></li>
<li><label>World</label></li>
如果您想定位带有文本“Hello”的 label 的父 <li>
元素,使用 locator.filter() 是最好的方法
- 同步
- 异步
child = page.get_by_text("Hello")
parent = page.get_by_role("listitem").filter(has=child)
child = page.get_by_text("Hello")
parent = page.get_by_role("listitem").filter(has=child)
或者,如果找不到适合父元素的定位器,请使用 xpath=..
。请注意,此方法不可靠,因为对 DOM 结构的任何更改都会破坏您的测试。尽可能优先使用 locator.filter()。
- 同步
- 异步
parent = page.get_by_text("Hello").locator('xpath=..')
parent = page.get_by_text("Hello").locator('xpath=..')
React 定位器
React 定位器是实验性的,并以 _
为前缀。未来功能可能会发生变化。
React 定位器允许通过组件名称和属性值查找元素。语法与CSS 属性选择器非常相似,并支持所有 CSS 属性选择器操作符。
在 React 定位器中,组件名称使用 CamelCase(驼峰式大小写)转写。
- 同步
- 异步
page.locator("_react=BookItem").click()
await page.locator("_react=BookItem").click()
更多示例
- 按 组件 匹配:
_react=BookItem
- 按组件和 精确属性值 匹配,区分大小写:
_react=BookItem[author = "Steven King"]
- 仅按属性值匹配,不区分大小写:
_react=[author = "steven king" i]
- 按组件和 truthy 属性值 匹配:
_react=MyButton[enabled]
- 按组件和 布尔值 匹配:
_react=MyButton[enabled = false]
- 按属性 值子字符串 匹配:
_react=[author *= "King"]
- 按组件和 多个属性 匹配:
_react=BookItem[author *= "king" i][year = 1990]
- 按 嵌套 属性值匹配:
_react=[some.nested.value = 12]
- 按组件和属性值 前缀 匹配:
_react=BookItem[author ^= "Steven"]
- 按组件和属性值 后缀 匹配:
_react=BookItem[author $= "Steven"]
- 按组件和 key 匹配:
_react=BookItem[key = '2']
- 按属性值 正则表达式 匹配:
_react=[author = /Steven(\\s+King)?/i]
要查找树中的 React 元素名称,请使用 React DevTools。
React 定位器支持 React 15 及以上版本。
React 定位器和 React DevTools 仅适用于 未压缩的 应用构建。
Vue 定位器
Vue 定位器是实验性的,并以 _
为前缀。未来功能可能会发生变化。
Vue 定位器允许通过组件名称和属性值查找元素。语法与CSS 属性选择器非常相似,并支持所有 CSS 属性选择器操作符。
在 Vue 定位器中,组件名称使用 kebab-case(烤肉串式大小写)转写。
- 同步
- 异步
page.locator("_vue=book-item").click()
await page.locator("_vue=book-item").click()
更多示例
- 按 组件 匹配:
_vue=book-item
- 按组件和 精确属性值 匹配,区分大小写:
_vue=book-item[author = "Steven King"]
- 仅按属性值匹配,不区分大小写:
_vue=[author = "steven king" i]
- 按组件和 truthy 属性值 匹配:
_vue=my-button[enabled]
- 按组件和 布尔值 匹配:
_vue=my-button[enabled = false]
- 按属性 值子字符串 匹配:
_vue=[author *= "King"]
- 按组件和 多个属性 匹配:
_vue=book-item[author *= "king" i][year = 1990]
- 按 嵌套 属性值匹配:
_vue=[some.nested.value = 12]
- 按组件和属性值 前缀 匹配:
_vue=book-item[author ^= "Steven"]
- 按组件和属性值 后缀 匹配:
_vue=book-item[author $= "Steven"]
- 按属性值 正则表达式 匹配:
_vue=[author = /Steven(\\s+King)?/i]
要查找树中的 Vue 元素名称,请使用 Vue DevTools。
Vue 定位器支持 Vue2 及以上版本。
Vue 定位器和 React DevTools 仅适用于 未压缩的 应用构建。
XPath 定位器
我们建议优先使用用户可见的定位器,例如文本或可访问角色,而不是使用与实现绑定且在页面更改时容易失效的 XPath 定位器。
XPath 定位器等同于调用Document.evaluate
。
- 同步
- 异步
page.locator("xpath=//button").click()
await page.locator("xpath=//button").click()
任何以 //
或 ..
开头的选择器字符串都被视为 XPath 选择器。例如,Playwright 将 '//html/body'
转换为 'xpath=//html/body'
。
XPath 不穿透 Shadow DOM 根。
XPath 联合
管道操作符 (|
) 可用于在 XPath 中指定多个选择器。它将匹配该列表中任一选择器可以选中的所有元素。
- 同步
- 异步
# Waits for either confirmation dialog or load spinner.
page.locator("//span[contains(@class, 'spinner__loading')]|//div[@id='confirmation']").wait_for()
# Waits for either confirmation dialog or load spinner.
await page.locator("//span[contains(@class, 'spinner__loading')]|//div[@id='confirmation']").wait_for()
标签到表单控件的重定向
我们建议使用标签文本定位,而不是依赖于标签到控件的重定向。
Playwright 中的目标输入操作会自动区分标签和控件,因此您可以定位标签来对关联的控件执行操作。
例如,考虑以下 DOM 结构:<label for="password">Password:</label><input id="password" type="password">
。您可以使用 page.get_by_text() 通过其“Password”文本定位标签。但是,以下操作将在输入而不是标签上执行
- locator.click() 将点击标签并自动聚焦输入字段;
- locator.fill() 将填充输入字段;
- locator.input_value() 将返回输入字段的值;
- locator.select_text() 将选中输入字段中的文本;
- locator.set_input_files() 将为
type=file
的输入字段设置文件; - locator.select_option() 将从选择框中选择一个选项。
- 同步
- 异步
# Fill the input by targeting the label.
page.get_by_text("Password").fill("secret")
# Fill the input by targeting the label.
await page.get_by_text("Password").fill("secret")
但是,其他方法将定位标签本身,例如 expect(locator).to_have_text() 将断言标签的文本内容,而不是输入字段。
- 同步
- 异步
# Fill the input by targeting the label.
expect(page.locator("label")).to_have_text("Password")
# Fill the input by targeting the label.
await expect(page.locator("label")).to_have_text("Password")
旧版文本定位器
我们推荐使用现代文本定位器。
旧版文本定位器匹配包含传入文本的元素。
- 同步
- 异步
page.locator("text=Log in").click()
await page.locator("text=Log in").click()
旧版文本定位器有几种变体
-
text=Log in
- 默认匹配不区分大小写,会修剪空白并搜索子字符串。例如,text=Log
匹配<button>Log in</button>
。- 同步
- 异步
page.locator("text=Log in").click()
await page.locator("text=Log in").click()
-
text="Log in"
- 文本主体可以用单引号或双引号进行转义,以搜索修剪空白后内容完全一致的文本节点。例如,
text="Log"
不匹配<button>Log in</button>
,因为<button>
包含一个文本节点“Log in”,它不等于“Log”。但是,text="Log"
匹配<button> Log <span>in</span></button>
,因为<button>
包含一个文本节点“ Log ”。此精确模式意味着区分大小写匹配,因此text="Download"
不匹配<button>download</button>
。带引号的主体遵循常规的转义规则,例如,在双引号字符串中使用
\"
来转义双引号:text="foo\"bar"
。- 同步
- 异步
page.locator("text='Log in'").click()
await page.locator("text='Log in'").click()
-
/Log\s*in/i
- 主体可以是包装在/
符号中的类似 JavaScript 的正则表达式。例如,text=/Log\s*in/i
匹配<button>Login</button>
和<button>log IN</button>
。- 同步
- 异步
page.locator("text=/Log\s*in/i").click()
await page.locator("text=/Log\s*in/i").click()
以引号(单引号或双引号)开头和结尾的字符串选择器被假定为旧版文本定位器。例如,“Log in”在内部被转换为 text="Log in"
。
匹配总是会规范化空白字符。例如,它会将多个空格变成一个,将换行符变成空格,并忽略开头和结尾的空白字符。
类型为 button
和 submit
的输入元素是根据其 value
进行匹配,而不是文本内容。例如,text=Log in
匹配 <input type=button value="Log in">
。
id, data-testid, data-test-id, data-test 选择器
我们建议使用测试 ID 定位。
Playwright 支持使用特定属性选择元素的简写形式。目前仅支持以下属性
id
data-testid
data-test-id
data-test
- 同步
- 异步
# Fill an input with the id "username"
page.locator('id=username').fill('value')
# Click an element with data-test-id "submit"
page.locator('data-test-id=submit').click()
# Fill an input with the id "username"
await page.locator('id=username').fill('value')
# Click an element with data-test-id "submit"
await page.locator('data-test-id=submit').click()
属性选择器不是 CSS 选择器,因此不支持 :enabled
等 CSS 特有内容。要获得更多功能,请使用合适的 css 选择器,例如 css=[data-test="login"]:enabled
。
链式选择器
我们建议使用链式定位器。
定义为 engine=body
或简写形式的选择器可以与 >>
标记结合使用,例如 selector1 >> selector2 >> selectors3
。当选择器链式组合时,下一个选择器相对于前一个选择器的结果进行查询。
例如,
css=article >> css=.bar > .baz >> css=span[attr=value]
等同于
document
.querySelector('article')
.querySelector('.bar > .baz')
.querySelector('span[attr=value]');
如果选择器主体需要包含 >>
,应在字符串内部进行转义,以免与链式分隔符混淆,例如 text="some >> text"
。
中间匹配项
我们建议使用另一个定位器进行过滤来定位包含其他元素的元素。
默认情况下,链式选择器解析为由最后一个选择器查询到的元素。选择器可以以 *
为前缀,以捕获由中间选择器查询到的元素。
例如,css=article >> text=Hello
捕获文本为 Hello 的元素,而 *css=article >> text=Hello
(注意 *
)捕获包含文本为 Hello 的元素的 article
元素。