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.

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

  • selector starting with // 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.
  1. // queries 'div' css selector
  2. const handle = await page.$('css=div');
  3. // queries '//html/body/div' xpath selector
  4. const handle = await page.$('xpath=//html/body/div');
  5. // queries '"foo"' text selector
  6. const handle = await page.$('text="foo"');
  7. // queries 'span' css selector inside the result of '//html/body/div' xpath selector
  8. const handle = await page.$('xpath=//html/body/div >> css=span');
  9. // converted to 'css=div'
  10. const handle = await page.$('div');
  11. // converted to 'xpath=//html/body/div'
  12. const handle = await page.$('//html/body/div');
  13. // converted to 'text="foo"'
  14. const handle = await page.$('"foo"');
  15. // queries 'span' css selector inside the div handle
  16. const handle = await divHandle.$('css=span');