跳到主要內容

Selectors

選取器可以用於安裝自訂選取器引擎。請參閱擴充性以了解更多資訊。


方法

register

在 v1.9 之前新增 selectors.register

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

用法

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

// 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" +
" // 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);
Browser browser = playwright.firefox().launch();
Page page = browser.newPage();
page.setContent("<div><button>Click me</button></div>");
// Use the selector prefixed with its name.
Locator button = page.locator("tag=button");
// Combine it with built-in locators.
page.locator("tag=div").getByText("Click me").click();
// Can use it in any methods supporting selectors.
int buttonCount = (int) page.locator("tag=button").count();
browser.close();

引數

  • name String#

    在選取器中用作前綴的名稱,例如 {name: 'foo'} 啟用 foo=myselectorbody 選取器。可能僅包含 [a-zA-Z0-9_] 字元。

  • script String | Path#

    評估為選取器引擎實例的腳本。該腳本在頁面上下文中評估。

  • options Selectors.RegisterOptions (選用)

    • setContentScript boolean (選用)#

      是否在隔離的 JavaScript 環境中執行此選取器引擎。此環境可以存取相同的 DOM,但不能存取框架腳本中的任何 JavaScript 物件。預設為 false。請注意,當此引擎與其他已註冊的引擎一起使用時,不保證作為內容腳本執行。

傳回


setTestIdAttribute

新增於:v1.27 selectors.setTestIdAttribute

定義要在 Page.getByTestId() 中使用的自訂屬性名稱。預設使用 data-testid

用法

Selectors.setTestIdAttribute(attributeName);

引數

  • attributeName String#

    測試 ID 屬性名稱。