可擴展性
自訂選取器引擎
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()