延展性
自訂選擇器引擎
Playwright 支援自訂選擇器引擎,已註冊於 selectors.register()。
選擇器引擎應該具有以下屬性:
query
函式來查詢相對於root
的第一個符合selector
的元素。queryAll
函式來查詢相對於root
的所有符合selector
的元素。
預設情況下,引擎直接在框架的 JavaScript 上下文中執行,例如,可以呼叫應用程式定義的函式。要將引擎與框架中的任何 JavaScript 隔離,但保留對 DOM 的訪問,請使 用 {contentScript: true}
選項註冊引擎。內容腳本引擎更安全,因為它受到任何對全域物件的篡改保護,例如更改 Node.prototype
方法。所有內建選擇器引擎都以內容腳本形式執行。請注意,當引擎與其他自定義引擎一起使用時,作為內容腳本執行並不保證。
建立頁面之前必須註冊選擇器。
註冊選擇器引擎的範例,該引擎根據標籤名稱查詢元素:
- Sync
- Async
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()