Skip to content

Commit c9544b9

Browse files
authored
docs: add documentation for selector engines (#752)
1 parent f44d660 commit c9544b9

File tree

2 files changed

+149
-9
lines changed

2 files changed

+149
-9
lines changed

docs/api.md

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3038,22 +3038,24 @@ Selectors can be used to install custom selector engines. See [Working with sele
30383038
<!-- GEN:stop -->
30393039

30403040
#### selectors.register(engineFunction[, ...args])
3041-
- `engineFunction` <[function]|[string]> Function which evaluates to a selector engine instance.
3041+
- `engineFunction` <[function]|[string]> Function that evaluates to a selector engine instance.
30423042
- `...args` <...[Serializable]> Arguments to pass to `engineFunction`.
30433043
- returns: <[Promise]>
30443044

3045-
An example of registering selector engine which selects nodes based on tag name:
3045+
An example of registering selector engine that queries elements based on a tag name:
30463046
```js
30473047
const { selectors, firefox } = require('playwright'); // Or 'chromium' or 'webkit'.
30483048

30493049
(async () => {
3050-
const createTagSelector = () => ({
3050+
// Must be a function that evaluates to a selector engine instance.
3051+
const createTagNameEngine = () => ({
30513052
// Selectors will be prefixed with "tag=".
30523053
name: 'tag',
30533054

3054-
// Creates a selector which matches given target when queried at the root.
3055+
// Creates a selector that matches given target when queried at the root.
3056+
// Can return undefined if unable to create one.
30553057
create(root, target) {
3056-
return target.tagName;
3058+
return root.querySelector(target.tagName) === target ? target.tagName : undefined;
30573059
},
30583060

30593061
// Returns the first element matching given selector in the root's subtree.
@@ -3067,7 +3069,8 @@ const { selectors, firefox } = require('playwright'); // Or 'chromium' or 'webk
30673069
}
30683070
});
30693071

3070-
await selectors.register(createTagSelector);
3072+
// Register the engine.
3073+
await selectors.register(createTagNameEngine);
30713074

30723075
const browser = await firefox.launch();
30733076
const context = await browser.newContext();
@@ -3755,11 +3758,11 @@ WebKit browser instance does not expose WebKit-specific features.
37553758

37563759
Selector describes an element in the page. It can be used to obtain `ElementHandle` (see [page.$()](#pageselector) for example) or shortcut element operations to avoid intermediate handle (see [page.click()](#pageclickselector-options) for example).
37573760

3758-
Selector has the following format: `engine=body [>> engine=body]*`. Here `engine` is one of the supported selector engines (currently, either `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.
3761+
Selector has the following format: `engine=body [>> engine=body]*`. Here `engine` is one of the supported [selector engines](selectors.md) (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.
37593762

37603763
For convenience, selectors in the wrong format are heuristically converted to the right format:
37613764
- selector starting with `//` is assumed to be `xpath=selector`;
3762-
- selector starting with `"` is assumed to be `zs=selector`;
3765+
- selector starting with `"` is assumed to be `text=selector`;
37633766
- otherwise selector is assumed to be `css=selector`.
37643767

37653768
```js
@@ -3781,7 +3784,7 @@ const handle = await page.$('div');
37813784
// converted to 'xpath=//html/body/div'
37823785
const handle = await page.$('//html/body/div');
37833786

3784-
// converted to 'zs="foo"'
3787+
// converted to 'text="foo"'
37853788
const handle = await page.$('"foo"');
37863789

37873790
// queries 'span' css selector inside the div handle

docs/selectors.md

Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
# Selector engines
2+
3+
Playwright supports multiple selector engines used to query elements in the web page.
4+
5+
Selector can be used to obtain `ElementHandle` (see [page.$()](api.md#pageselector) for example) or shortcut element operations to avoid intermediate handle (see [page.click()](api.md#pageclickselector-options) for example).
6+
7+
## Selector syntax
8+
9+
Selector is a string that consists of one or more clauses separated by `>>` token, e.g. `clause1 >> clause2 >> clause3`. When multiple clauses are present, next one is queried relative to the previous one's result.
10+
11+
Each clause contains a selector engine name and selector body, e.g. `engine=body`. Here `engine` is one of the supported engines (e.g. `css` or a custom one). Selector `body` follows the format of the particular engine, e.g. for `css` engine it should be a [css selector](https://developer.mozilla.org/en/docs/Web/CSS/CSS_Selectors). Body format is assumed to ignore leading and trailing whitespaces, so that extra whitespace can be added for readability. If selector engine needs to include `>>` in the body, it should be escaped inside a string to not be confused with clause separator, e.g. `text="some >> text"`.
12+
13+
For example,
14+
```
15+
css=article >> css=.bar > .baz >> css=span[attr=value]
16+
```
17+
is equivalent to
18+
```js
19+
document
20+
.querySelector('article')
21+
.querySelector('.bar > .baz')
22+
.querySelector('span[attr=value]')
23+
```
24+
25+
For convenience, selectors in the wrong format are heuristically converted to the right format:
26+
- selector starting with `//` is assumed to be `xpath=selector`;
27+
- selector starting with `"` is assumed to be `text=selector`;
28+
- otherwise selector is assumed to be `css=selector`.
29+
30+
## Examples
31+
32+
```js
33+
// queries 'div' css selector
34+
const handle = await page.$('css=div');
35+
36+
// queries '//html/body/div' xpath selector
37+
const handle = await page.$('xpath=//html/body/div');
38+
39+
// queries '"foo"' zs selector
40+
const handle = await page.$('zs="foo"');
41+
42+
// queries 'span' css selector inside the result of '//html/body/div' xpath selector
43+
const handle = await page.$('xpath=//html/body/div >> css=span');
44+
45+
// converted to 'css=div'
46+
const handle = await page.$('div');
47+
48+
// converted to 'xpath=//html/body/div'
49+
const handle = await page.$('//html/body/div');
50+
51+
// converted to 'text="foo"'
52+
const handle = await page.$('"foo"');
53+
54+
// queries 'span' css selector inside the div handle
55+
const handle = await divHandle.$('css=span');
56+
```
57+
58+
## Built-in selector engines
59+
60+
### css
61+
62+
CSS engine is equivalent to [`Document.querySelector`](https://developer.mozilla.org/en/docs/Web/API/Document/querySelector). Example: `css=.article > span:nth-child(2) li`.
63+
64+
> **NOTE** Malformed selector not starting with `//` nor with `#` is automatically transformed to css selector. For example, Playwright converts `page.$('span > button')` to `page.$('css=span > button')`. Selectors starting with `#` are converted to [text](#text). Selectors starting with `//` are converted to [xpath](#xpath).
65+
66+
### xpath
67+
68+
XPath engine is equivalent to [`Document.evaluate`](https://developer.mozilla.org/en/docs/Web/API/Document/evaluate). Example: `xpath=//html/body`.
69+
70+
> **NOTE** Malformed selector starting with `//` is automatically transformed to xpath selector. For example, Playwright converts `page.$('//html/body')` to `page.$('xpath=//html/body')`.
71+
72+
### text
73+
74+
Text engine finds an element that contains a text node with passed text. Example: `text=Login`.
75+
- By default, the match is case-insensitive, and ignores leading/trailing whitespace. This means `text= Login` matches `<button>loGIN </button>`.
76+
- Text body can be escaped with double quotes for precise matching, insisting on specific whitespace and case. This means `text="Login "` will only match `<button>Login </button>` with exactly one space after "Login".
77+
- Text body can also be a JavaScript-like regex wrapped in `/` symbols. This means `text=/^\\s*Login$/i` will match `<button> loGIN</button>` with any number of spaces before "Login" and no spaces after.
78+
79+
> **NOTE** Malformed selector starting with `"` is automatically transformed to text selector. For example, Playwright converts `page.click('"Login"')` to `page.click('text="Login"')`.
80+
81+
### id, data-testid, data-test-id, data-test
82+
83+
Id engines are selecting based on the corresponding atrribute value. For example: `data-test-id=foo` is equivalent to `querySelector('*[data-test-id=foo]')`.
84+
85+
### zs
86+
87+
ZSelector is an experimental engine that tries to make selectors survive future refactorings. Example: `zs=div ~ "Login"`.
88+
89+
TODO: write more.
90+
91+
## Custom selector engines
92+
93+
Playwright supports custom selector engines, registered with [selectors.register(engineFunction[, ...args])](api.md#selectorsregisterenginefunction-args).
94+
95+
Selector engine should have the following properties:
96+
97+
- `name` Selector name used in selector strings.
98+
- `create` Function to create a relative selector from `root` (root is either a `Document`, `ShadowRoot` or `Element`) to a `target` element.
99+
- `query` Function to query first element matching `selector` relative to the `root`.
100+
- `queryAll` Function to query all elements matching `selector` relative to the `root`.
101+
102+
An example of registering selector engine that queries elements based on a tag name:
103+
```js
104+
// Must be a function that evaluates to a selector engine instance.
105+
const createTagNameEngine = () => ({
106+
// Selectors will be prefixed with "tag=".
107+
name: 'tag',
108+
109+
// Creates a selector that matches given target when queried at the root.
110+
// Can return undefined if unable to create one.
111+
create(root, target) {
112+
return root.querySelector(target.tagName) === target ? target.tagName : undefined;
113+
},
114+
115+
// Returns the first element matching given selector in the root's subtree.
116+
query(root, selector) {
117+
return root.querySelector(selector);
118+
},
119+
120+
// Returns all elements matching given selector in the root's subtree.
121+
queryAll(root, selector) {
122+
return Array.from(root.querySelectorAll(selector));
123+
}
124+
});
125+
126+
// Register the engine.
127+
await selectors.register(createTagNameEngine);
128+
129+
// Now we can use 'tag=' selectors.
130+
const button = await page.$('tag=button');
131+
132+
// We can combine it with other selector engines.
133+
await page.click('tag=div >> text="Click me"');
134+
135+
// We can use it in any methods supporting selectors.
136+
const buttonCount = await page.$$eval('tag=button', buttons => buttons.length);
137+
```

0 commit comments

Comments
 (0)