擴充性
自訂選取器引擎
Playwright 支援自訂選取器引擎,透過 Selectors.RegisterAsync() 註冊。
選取器引擎應具有以下屬性
query
函數,用於查詢相對於root
的第一個符合selector
的元素。queryAll
函數,用於查詢相對於root
的所有符合selector
的元素。
預設情況下,引擎直接在框架的 JavaScript 環境中執行,並且例如,可以呼叫應用程式定義的函數。為了將引擎與框架中的任何 JavaScript 隔離,但保留對 DOM 的訪問權限,請使用 {contentScript: true}
選項註冊引擎。內容腳本引擎更安全,因為它可以防止任何篡改全域物件,例如更改 Node.prototype
方法。所有內建的選取器引擎都作為內容腳本執行。請注意,當引擎與其他自訂引擎一起使用時,不能保證作為內容腳本執行。
選取器必須在建立頁面之前註冊。
註冊選取器引擎的範例,該引擎根據標籤名稱查詢元素
// Register the engine. Selectors will be prefixed with "tag=".
// The script is evaluated in the page context.
await playwright.Selectors.Register("tag", new() {
Script = @"
// 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));
}
}"
});
// Now we can use "tag=" selectors.
await page.Locator("tag=button").ClickAsync();
// We can combine it with built-in locators.
await page.Locator("tag=div").GetByText("Click me").ClickAsync();