延展性
自訂選擇器引擎
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()