跳到主要內容

擴充性

自訂選取器引擎

Playwright 支援自訂選取器引擎,透過 Selectors.register() 註冊。

選取器引擎應具有以下屬性

  • query 函數,用於查詢相對於 root 的第一個符合 selector 的元素。
  • queryAll 函數,用於查詢相對於 root 的所有符合 selector 的元素。

預設情況下,引擎直接在框架的 JavaScript 環境中執行,並且,例如,可以調用應用程式定義的函數。為了將引擎與框架中的任何 JavaScript 隔離,但保留對 DOM 的訪問權限,請使用 {contentScript: true} 選項註冊引擎。內容腳本引擎更安全,因為它可以防止任何篡改全域物件,例如更改 Node.prototype 方法。所有內建的選取器引擎都作為內容腳本執行。請注意,當引擎與其他自訂引擎一起使用時,不保證作為內容腳本執行。

選取器必須在建立頁面之前註冊。

註冊選取器引擎的範例,該引擎根據標籤名稱查詢元素

// Must be a script that evaluates to a selector engine instance.  The script is evaluated in the page context.
String createTagNameEngine = "{\n" +
" // Returns the first element matching given selector in the root's subtree.\n" +
" query(root, selector) {\n" +
" return root.querySelector(selector);\n" +
" },\n" +
"\n" +
" // Returns all elements matching given selector in the root's subtree.\n" +
" queryAll(root, selector) {\n" +
" return Array.from(root.querySelectorAll(selector));\n" +
" }\n" +
"}";

// Register the engine. Selectors will be prefixed with "tag=".
playwright.selectors().register("tag", createTagNameEngine);

// Now we can use "tag=" selectors.
Locator button = page.locator("tag=button");
button.click();

// We can combine it with built-in locators.
page.locator("tag=div").getByText("Click me").click();

// We can use it in any methods supporting selectors.
int buttonCount = (int) page.locator("tag=button").count();