可扩展性
自定义选择器引擎
Playwright 支持自定义选择器引擎,这些引擎通过 selectors.register() 注册。
选择器引擎应具有以下属性
query
函数,用于查询相对于root
的第一个匹配selector
的元素。queryAll
函数,用于查询相对于root
的所有匹配selector
的元素。
默认情况下,引擎直接在框架的 JavaScript 上下文中运行,例如,可以调用应用程序定义的函数。为了隔离引擎与框架中的任何 JavaScript,但保留对 DOM 的访问权限,请使用 {contentScript: true}
选项注册引擎。内容脚本引擎更安全,因为它受到保护,免受对全局对象的任何篡改,例如更改 Node.prototype
方法。所有内置选择器引擎都作为内容脚本运行。请注意,当引擎与其他自定义引擎一起使用时,无法保证以内容脚本运行。
必须在创建页面之前注册选择器。
一个注册选择器引擎的示例,该引擎根据标签名称查询元素
- 同步
- 异步
tag_selector = """
// Must evaluate to a selector engine instance.
{
// Returns the first element matching given selector in the root's subtree.
query(root, selector) {
return root.querySelector(selector);
},
// Returns all elements matching given selector in the root's subtree.
queryAll(root, selector) {
return Array.from(root.querySelectorAll(selector));
}
}"""
# register the engine. selectors will be prefixed with "tag=".
playwright.selectors.register("tag", tag_selector)
# now we can use "tag=" selectors.
button = page.locator("tag=button")
button.click()
# we can combine it with built-in locators.
page.locator("tag=div").get_by_text("click me").click()
# we can use it in any methods supporting selectors.
button_count = page.locator("tag=button").count()
tag_selector = """
// Must evaluate to a selector engine instance.
{
// Returns the first element matching given selector in the root's subtree.
query(root, selector) {
return root.querySelector(selector);
},
// Returns all elements matching given selector in the root's subtree.
queryAll(root, selector) {
return Array.from(root.querySelectorAll(selector));
}
}"""
# register the engine. selectors will be prefixed with "tag=".
await playwright.selectors.register("tag", tag_selector)
# now we can use "tag=" selectors.
button = page.locator("tag=button")
await button.click()
# we can combine it with built-in locators.
await page.locator("tag=div").get_by_text("click me").click()
# we can use it in any methods supporting selectors.
button_count = await page.locator("tag=button").count()