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 bexpath=selector
; - selector starting and ending with a quote (either
"
or'
) is assumed to betext=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' css selector inside the div handle
const handle = await divHandle.$('css=span');