Skip to content

Commit e85f278

Browse files
authored
docs: more python docs and snippets (#5021)
1 parent 61b0dbb commit e85f278

17 files changed

+1079
-132
lines changed

docs/src/api/class-accessibility.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,10 @@ assistive technology such as [screen readers](https://en.wikipedia.org/wiki/Scre
77
Accessibility is a very platform-specific thing. On different platforms, there are different screen readers that might
88
have wildly different output.
99

10-
Blink - Chromium's rendering engine - has a concept of "accessibility tree", which is then translated into different
11-
platform-specific APIs. Accessibility namespace gives users access to the Blink Accessibility Tree.
10+
Rendering engines of Chromium, Firefox and Webkit have a concept of "accessibility tree", which is then translated into different
11+
platform-specific APIs. Accessibility namespace gives access to this Accessibility Tree.
1212

13-
Most of the accessibility tree gets filtered out when converting from Blink AX Tree to Platform-specific AX-Tree or by
13+
Most of the accessibility tree gets filtered out when converting from internal browser AX Tree to Platform-specific AX-Tree or by
1414
assistive technologies themselves. By default, Playwright tries to approximate this filtering, exposing only the
1515
"interesting" nodes of the tree.
1616

@@ -98,7 +98,7 @@ def find_focused_node(node):
9898
snapshot = await page.accessibility.snapshot()
9999
node = find_focused_node(snapshot)
100100
if node:
101-
print(node["name"])
101+
print(node["name"])
102102
```
103103

104104
```python sync
@@ -113,7 +113,7 @@ def find_focused_node(node):
113113
snapshot = page.accessibility.snapshot()
114114
node = find_focused_node(snapshot)
115115
if node:
116-
print(node["name"])
116+
print(node["name"])
117117
```
118118

119119
### option: Accessibility.snapshot.interestingOnly

docs/src/api/class-browser.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
# class: Browser
2-
* extends: [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter)
2+
* extends: [EventEmitter]
33

44
A Browser is created via [`method: BrowserType.launch`]. An example of using a [Browser] to create a [Page]:
55

docs/src/api/class-browsercontext.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
# class: BrowserContext
2-
* extends: [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter)
2+
* extends: [EventEmitter]
33

44
BrowserContexts provide a way to operate multiple independent browser sessions.
55

@@ -567,7 +567,7 @@ await browser.close();
567567
```python async
568568
context = await browser.new_context()
569569
page = await context.new_page()
570-
await context.route(r"(\.png$)|(\.jpg$)", lambda route => route.abort())
570+
await context.route(r"(\.png$)|(\.jpg$)", lambda route: route.abort())
571571
page = await context.new_page()
572572
await page.goto("https://example.com")
573573
await browser.close()
@@ -576,7 +576,7 @@ await browser.close()
576576
```python sync
577577
context = browser.new_context()
578578
page = context.new_page()
579-
context.route(r"(\.png$)|(\.jpg$)", lambda route => route.abort())
579+
context.route(r"(\.png$)|(\.jpg$)", lambda route: route.abort())
580580
page = await context.new_page()
581581
page = context.new_page()
582582
page.goto("https://example.com")

docs/src/api/class-cdpsession.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
# class: CDPSession
2-
* extends: [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter)
2+
* extends: [EventEmitter]
33

44
The `CDPSession` instances are used to talk raw Chrome Devtools Protocol:
55
* protocol methods can be called with `session.send` method.

docs/src/api/class-page.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
# class: Page
2-
* extends: [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter)
2+
* extends: [EventEmitter]
33

44
Page provides methods to interact with a single tab in a [Browser], or an
55
[extension background page](https://developer.chrome.com/extensions/background_pages) in Chromium. One [Browser]

docs/src/api/python.md

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,22 @@
1+
## async method: Playwright.start
2+
* langs: python
3+
4+
Starts a new instance of Playwright without using the Python context manager. This is useful in REPL applications. Requires [`method: Playwright.stop`] to be called to cleanup resources.
5+
6+
```py
7+
>>> from playwright.sync_api import sync_playwright
8+
9+
>>> playwright = sync_playwright().start()
10+
11+
>>> browser = playwright.chromium.launch()
12+
>>> page = browser.newPage()
13+
>>> page.goto("http://whatsmyuseragent.org/")
14+
>>> page.screenshot(path="example.png")
15+
>>> browser.close()
16+
17+
>>> playwright.stop()
18+
```
19+
120
## async method: Playwright.stop
221
* langs: python
322

@@ -202,13 +221,13 @@ from a `setTimeout`. Consider this example:
202221

203222
```python async
204223
async with page.expect_navigation():
205-
await page.click("a.delayed-navigation") # Clicking the link will indirectly cause a navigation
224+
await page.click("a.delayed-navigation") # Clicking the link will indirectly cause a navigation
206225
# Context manager waited for the navigation to happen.
207226
```
208227

209228
```python sync
210229
with page.expect_navigation():
211-
page.click("a.delayed-navigation") # Clicking the link will indirectly cause a navigation
230+
page.click("a.delayed-navigation") # Clicking the link will indirectly cause a navigation
212231
# Context manager waited for the navigation to happen.
213232
```
214233

@@ -236,13 +255,13 @@ from a `setTimeout`. Consider this example:
236255

237256
```python async
238257
async with frame.expect_navigation():
239-
await frame.click("a.delayed-navigation") # Clicking the link will indirectly cause a navigation
258+
await frame.click("a.delayed-navigation") # Clicking the link will indirectly cause a navigation
240259
# Context manager waited for the navigation to happen.
241260
```
242261

243262
```python sync
244263
with frame.expect_navigation():
245-
frame.click("a.delayed-navigation") # Clicking the link will indirectly cause a navigation
264+
frame.click("a.delayed-navigation") # Clicking the link will indirectly cause a navigation
246265
# Context manager waited for the navigation to happen.
247266
```
248267

docs/src/assertions.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ title: "Assertions"
44
---
55

66
The Playwright API can be used to read element contents and properties for test assertions. These values are fetched from the browser page and asserted in
7-
Node.js.
7+
your script.
88

99
<!-- TOC -->
1010

docs/src/emulation.md

Lines changed: 27 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -4,20 +4,22 @@ title: "Device and environment emulation"
44
---
55

66
Playwright allows overriding various parameters of the device where the browser is running:
7-
- viewport size, device scale factor, touch support
8-
- locale, timezone
9-
- color scheme
10-
- geolocation
7+
- viewport size, device scale factor, touch support
8+
- locale, timezone
9+
- color scheme
10+
- geolocation
1111

12-
Most of these parameters are configured during the browser context construction, but some of them such as viewport size can be changed for individual pages.
12+
Most of these parameters are configured during the browser context construction, but some of them such as viewport size
13+
can be changed for individual pages.
1314

1415
<!-- TOC -->
1516

1617
<br/>
1718

1819
## Devices
1920

20-
Playwright comes with a registry of device parameters for selected mobile devices. It can be used to simulate browser behavior on a mobile device:
21+
Playwright comes with a registry of device parameters for selected mobile devices. It can be used to simulate browser
22+
behavior on a mobile device:
2123

2224
```js
2325
const { chromium, devices } = require('playwright');
@@ -33,32 +35,36 @@ const context = await browser.newContext({
3335
import asyncio
3436
from playwright.async_api import async_playwright
3537

36-
async def main():
37-
async with async_playwright() as p:
38-
pixel_2 = p.devices['Pixel 2']
39-
browser = await p.webkit.launch(headless=False)
40-
context = await browser.new_context(
41-
**pixel_2,
42-
)
38+
async def run(playwright):
39+
pixel_2 = playwright.devices['Pixel 2']
40+
browser = await playwright.webkit.launch(headless=False)
41+
context = await browser.new_context(
42+
**pixel_2,
43+
)
4344

44-
asyncio.get_event_loop().run_until_complete(main())
45+
async def main():
46+
async with async_playwright() as playwright:
47+
await run(playwright)
48+
asyncio.run(main())
4549
```
4650

4751
```python sync
4852
from playwright.sync_api import sync_playwright
4953

50-
with sync_playwright() as p:
51-
pixel_2 = p.devices['Pixel 2']
52-
browser = p.webkit.launch(headless=False)
54+
def run(playwright):
55+
pixel_2 = playwright.devices['Pixel 2']
56+
browser = playwright.webkit.launch(headless=False)
5357
context = browser.new_context(
5458
**pixel_2,
5559
)
60+
61+
with sync_playwright() as playwright:
62+
run(playwright)
5663
```
5764

5865
All pages created in the context above will share the same device parameters.
5966

6067
#### API reference
61-
6268
- [`property: Playwright.devices`]
6369
- [`method: Browser.newContext`]
6470

@@ -87,7 +93,6 @@ context = browser.new_context(
8793
```
8894

8995
#### API reference
90-
9196
- [`method: Browser.newContext`]
9297

9398
<br/>
@@ -141,11 +146,9 @@ page.set_viewport_size(width=1600, height=1200)
141146
context = browser.new_context(
142147
viewport={ 'width': 2560, 'height': 1440 },
143148
device_scale_factor=2,
144-
145149
```
146150

147151
#### API reference
148-
149152
- [`method: Browser.newContext`]
150153
- [`method: Page.setViewportSize`]
151154

@@ -178,7 +181,6 @@ context = browser.new_context(
178181
```
179182

180183
#### API reference
181-
182184
- [`method: Browser.newContext`]
183185

184186
<br/>
@@ -248,14 +250,14 @@ context.clear_permissions()
248250
```
249251

250252
#### API reference
251-
252253
- [`method: Browser.newContext`]
253254
- [`method: BrowserContext.grantPermissions`]
254255
- [`method: BrowserContext.clearPermissions`]
255256

256257
<br/>
257258

258259
## Geolocation
260+
259261
Create a context with `"geolocation"` permissions granted:
260262

261263
```js
@@ -296,16 +298,14 @@ context.set_geolocation({"longitude": 29.979097, "latitude": 31.134256})
296298
**Note** you can only change geolocation for all pages in the context.
297299

298300
#### API reference
299-
300301
- [`method: Browser.newContext`]
301302
- [`method: BrowserContext.setGeolocation`]
302303

303304
<br/>
304305

305306
## Color scheme and media
306307

307-
Create a context with dark or light mode. Pages created in this context will
308-
follow this color scheme preference.
308+
Create a context with dark or light mode. Pages created in this context will follow this color scheme preference.
309309

310310
```js
311311
// Create context with dark mode
@@ -362,6 +362,5 @@ page.emulate_media(media='print')
362362
```
363363

364364
#### API reference
365-
366365
- [`method: Browser.newContext`]
367-
- [`method: Page.emulateMedia`]
366+
- [`method: Page.emulateMedia`]

docs/src/extensibility.md

Lines changed: 65 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,20 @@ title: "Extensibility"
1010
Playwright supports custom selector engines, registered with [`method: Selectors.register`].
1111

1212
Selector engine should have the following properties:
13-
14-
- `create` function to create a relative selector from `root` (root is either a `Document`, `ShadowRoot` or `Element`) to a `target` element.
13+
- `create` function to create a relative selector from `root` (root is either a `Document`, `ShadowRoot` or `Element`)
14+
to a `target` element.
1515
- `query` function to query first element matching `selector` relative to the `root`.
1616
- `queryAll` function to query all elements matching `selector` relative to the `root`.
1717

18-
By default the engine is run directly in the frame's JavaScript context and, for example, can call an application-defined function. To isolate the engine from any JavaScript in the frame, but leave access to the DOM, register the engine with `{contentScript: true}` option. Content script engine is safer because it is protected from any tampering with the global objects, for example altering `Node.prototype` methods. All built-in selector engines run as content scripts. Note that running as a content script is not guaranteed when the engine is used together with other custom engines.
18+
By default the engine is run directly in the frame's JavaScript context and, for example, can call an
19+
application-defined function. To isolate the engine from any JavaScript in the frame, but leave access to the DOM,
20+
register the engine with `{contentScript: true}` option. Content script engine is safer because it is protected from any
21+
tampering with the global objects, for example altering `Node.prototype` methods. All built-in selector engines run as
22+
content scripts. Note that running as a content script is not guaranteed when the engine is used together with other
23+
custom engines.
1924

2025
An example of registering selector engine that queries elements based on a tag name:
26+
2127
```js
2228
// Must be a function that evaluates to a selector engine instance.
2329
const createTagNameEngine = () => ({
@@ -44,3 +50,59 @@ await page.click('tag=div >> span >> "Click me"');
4450
// We can use it in any methods supporting selectors.
4551
const buttonCount = await page.$$eval('tag=button', buttons => buttons.length);
4652
```
53+
54+
```python async
55+
tag_selector = """
56+
// Must evaluate to a selector engine instance.
57+
{
58+
// Returns the first element matching given selector in the root's subtree.
59+
query(root, selector) {
60+
return root.querySelector(selector);
61+
},
62+
63+
// Returns all elements matching given selector in the root's subtree.
64+
queryAll(root, selector) {
65+
return Array.from(root.querySelectorAll(selector));
66+
}
67+
}"""
68+
69+
# register the engine. selectors will be prefixed with "tag=".
70+
await playwright.selectors.register("tag", tag_selector)
71+
72+
# now we can use "tag=" selectors.
73+
button = await page.query_selector("tag=button")
74+
75+
# we can combine it with other selector engines using `>>` combinator.
76+
await page.click("tag=div >> span >> "click me"")
77+
78+
# we can use it in any methods supporting selectors.
79+
button_count = await page.eval_on_selector_all("tag=button", buttons => buttons.length)
80+
```
81+
82+
```python sync
83+
tag_selector = """
84+
// Must evaluate to a selector engine instance.
85+
{
86+
// Returns the first element matching given selector in the root's subtree.
87+
query(root, selector) {
88+
return root.querySelector(selector);
89+
},
90+
91+
// Returns all elements matching given selector in the root's subtree.
92+
queryAll(root, selector) {
93+
return Array.from(root.querySelectorAll(selector));
94+
}
95+
}"""
96+
97+
# register the engine. selectors will be prefixed with "tag=".
98+
playwright.selectors.register("tag", tag_selector)
99+
100+
# now we can use "tag=" selectors.
101+
button = page.query_selector("tag=button")
102+
103+
# we can combine it with other selector engines using `>>` combinator.
104+
page.click("tag=div >> span >> "click me"")
105+
106+
# we can use it in any methods supporting selectors.
107+
button_count = page.eval_on_selector_all("tag=button", buttons => buttons.length)
108+
```

0 commit comments

Comments
 (0)