Version: 1.7.0

Working with selectors

Selector describes an element in the page. It can be used to obtain ElementHandle (see page.$() for example) or shortcut element operations to avoid intermediate handle (see page.click() for example).

Selector has the following format: engine=body [>> engine=body]*. Here engine is one of the supported selector engines (e.g. css or xpath), and body is a selector body in the format of the particular engine. When multiple engine=body clauses are present (separated by >>), next one is queried relative to the previous one's result.

Playwright also supports the following CSS extensions:

  • :text("string") - Matches elements that contain specific text node. Learn more about text selector.
  • :visible - Matches only visible elements. Learn more about visible selector.
  • :light(selector) - Matches in the light DOM only as opposite to piercing open shadow roots. Learn more about shadow piercing.

For convenience, selectors in the wrong format are heuristically converted to the right format:

  • selector starting with // or .. is assumed to be xpath=selector;
  • selector starting and ending with a quote (either " or ') is assumed to be text=selector;
  • otherwise selector is assumed to be css=selector.
// queries 'div' css selector
const handle = await page.$('css=div');
// queries '//html/body/div' xpath selector
const handle = await page.$('xpath=//html/body/div');
// queries '"foo"' text selector
const handle = await page.$('text="foo"');
// queries 'span' css selector inside the result of '//html/body/div' xpath selector
const handle = await page.$('xpath=//html/body/div >> css=span');
// converted to 'css=div'
const handle = await page.$('div');
// converted to 'xpath=//html/body/div'
const handle = await page.$('//html/body/div');
// converted to 'text="foo"'
const handle = await page.$('"foo"');
// queries '../span' xpath selector starting with the result of 'div' css selector
const handle = await page.$('div >> ../span');
// queries 'span' css selector inside the div handle
const handle = await divHandle.$('css=span');