Skip to main content

可扩展性

自定义选择器引擎

¥Custom selector engines

Playwright 支持自定义选择器引擎,已在 Selectors.register() 注册。

¥Playwright supports custom selector engines, registered with Selectors.register().

选择器引擎应具有以下属性:

¥Selector engine should have the following properties:

  • query 函数查询相对于 root 匹配 selector 的第一个元素。

    ¥query function to query first element matching selector relative to the root.

  • queryAll 函数查询相对于 root 匹配 selector 的所有元素。

    ¥queryAll function to query all elements matching selector relative to the root.

默认情况下,引擎直接在框架的 JavaScript 上下文中运行,例如,可以调用应用定义的函数。要将引擎与框架中的任何 JavaScript 隔离,但保留对 DOM 的访问权限,请使用 {contentScript: true} 选项注册引擎。内容脚本引擎更安全,因为它可以防止对全局对象的任何篡改,例如更改 Node.prototype 方法。所有内置选择器引擎都作为内容脚本运行。请注意,当引擎与其他自定义引擎一起使用时,不能保证作为内容脚本运行。

¥By default the engine is run directly in the frame's JavaScript context and, for example, can call an application-defined function. To isolate the engine from any JavaScript in the frame, but leave access to the DOM, register the engine with {contentScript: true} option. Content script engine is safer because it is protected from any tampering with the global objects, for example altering Node.prototype methods. All built-in selector engines run as content scripts. Note that running as a content script is not guaranteed when the engine is used together with other custom engines.

创建页面之前必须注册选择器。

¥Selectors must be registered before creating the page.

注册根据标签名称查询元素的选择器引擎的示例:

¥An example of registering selector engine that queries elements based on a tag name:

// 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();