可扩展性
自定义选择器引擎
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()