class: Selectors

Selectors can be used to install custom selector engines. See Working with selectors for more information.

selectors.register(name, script[, options])

  • 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.
  • script <function|string|Object> Script that evaluates to a selector engine instance.
  • options <Object>
    • contentScript <boolean> 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.
  • returns: <Promise>

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

  1. const { selectors, firefox } = require('playwright'); // Or 'chromium' or 'webkit'.
  2. (async () => {
  3. // Must be a function that evaluates to a selector engine instance.
  4. const createTagNameEngine = () => ({
  5. // Creates a selector that matches given target when queried at the root.
  6. // Can return undefined if unable to create one.
  7. create(root, target) {
  8. return root.querySelector(target.tagName) === target ? target.tagName : undefined;
  9. },
  10. // Returns the first element matching given selector in the root's subtree.
  11. query(root, selector) {
  12. return root.querySelector(selector);
  13. },
  14. // Returns all elements matching given selector in the root's subtree.
  15. queryAll(root, selector) {
  16. return Array.from(root.querySelectorAll(selector));
  17. }
  18. });
  19. // Register the engine. Selectors will be prefixed with "tag=".
  20. await selectors.register('tag', createTagNameEngine);
  21. const browser = await firefox.launch();
  22. const page = await browser.newPage();
  23. await page.goto('https://example.com');
  24. // Use the selector prefixed with its name.
  25. const button = await page.$('tag=button');
  26. // Combine it with other selector engines.
  27. await page.click('tag=div >> text="Click me"');
  28. // Can use it in any methods supporting selectors.
  29. const buttonCount = await page.$$eval('tag=button', buttons => buttons.length);
  30. await browser.close();
  31. })();