Skip to main content

Selectors

Selectors can be used to install custom selector engines. See extensibility for more information.


Methods

RegisterAsync

Added in: v1.8selectors.RegisterAsync

Usage

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

using Microsoft.Playwright;

using var playwright = await Playwright.CreateAsync();
// Script that evaluates to a selector engine instance. The script is evaluated in the page context.
await playwright.Selectors.RegisterAsync("tag", new()
{
Script = @"{
// 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));
}
}"
});

await using var browser = await playwright.Chromium.LaunchAsync();
var page = await browser.NewPageAsync();
await page.SetContentAsync("<div><button>Click me</button></div>");
// Use the selector prefixed with its name.
var button = page.Locator("tag=button");
// Combine it with other selector engines.
await page.Locator("tag=div >> text=\"Click me\"").ClickAsync();
// Can use it in any methods supporting selectors.
int buttonCount = await page.Locator("tag=button").CountAsync();

Arguments

  • name string#

    Name that is used in selectors as a prefix, e.g. {name: 'foo'} enables foo=myselectorbody selectors. May only contain [a-zA-Z0-9_] characters.

  • options SelectorsRegisterOptions? (optional)

    • ContentScript bool? (optional)#

      Whether to run this selector engine in isolated JavaScript environment. This environment has access to the same DOM, but not any JavaScript objects from the frame's scripts. Defaults to false. Note that running as a content script is not guaranteed when this engine is used together with other registered engines.

    • Path string? (optional)#

      Script that evaluates to a selector engine instance. The script is evaluated in the page context.

    • Script string? (optional)#

      Script that evaluates to a selector engine instance. The script is evaluated in the page context.


SetTestIdAttribute

Added in: v1.27selectors.SetTestIdAttribute

Defines custom attribute name to be used in Page.GetByTestId(). data-testid is used by default.

Usage

Selectors.SetTestIdAttribute(attributeName);

Arguments

  • attributeName string#

    Test id attribute name.