Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: more python docs and snippets #5021

Merged
merged 1 commit into from
Jan 14, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions docs/src/api/class-accessibility.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ assistive technology such as [screen readers](https://en.wikipedia.org/wiki/Scre
Accessibility is a very platform-specific thing. On different platforms, there are different screen readers that might
have wildly different output.

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

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

Expand Down Expand Up @@ -98,7 +98,7 @@ def find_focused_node(node):
snapshot = await page.accessibility.snapshot()
node = find_focused_node(snapshot)
if node:
print(node["name"])
print(node["name"])
```

```python sync
Expand All @@ -113,7 +113,7 @@ def find_focused_node(node):
snapshot = page.accessibility.snapshot()
node = find_focused_node(snapshot)
if node:
print(node["name"])
print(node["name"])
```

### option: Accessibility.snapshot.interestingOnly
Expand Down
2 changes: 1 addition & 1 deletion docs/src/api/class-browser.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# class: Browser
* extends: [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter)
* extends: [EventEmitter]

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

Expand Down
6 changes: 3 additions & 3 deletions docs/src/api/class-browsercontext.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# class: BrowserContext
* extends: [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter)
* extends: [EventEmitter]

BrowserContexts provide a way to operate multiple independent browser sessions.

Expand Down Expand Up @@ -567,7 +567,7 @@ await browser.close();
```python async
context = await browser.new_context()
page = await context.new_page()
await context.route(r"(\.png$)|(\.jpg$)", lambda route => route.abort())
await context.route(r"(\.png$)|(\.jpg$)", lambda route: route.abort())
page = await context.new_page()
await page.goto("https://example.com")
await browser.close()
Expand All @@ -576,7 +576,7 @@ await browser.close()
```python sync
context = browser.new_context()
page = context.new_page()
context.route(r"(\.png$)|(\.jpg$)", lambda route => route.abort())
context.route(r"(\.png$)|(\.jpg$)", lambda route: route.abort())
page = await context.new_page()
page = context.new_page()
page.goto("https://example.com")
Expand Down
2 changes: 1 addition & 1 deletion docs/src/api/class-cdpsession.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# class: CDPSession
* extends: [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter)
* extends: [EventEmitter]

The `CDPSession` instances are used to talk raw Chrome Devtools Protocol:
* protocol methods can be called with `session.send` method.
Expand Down
2 changes: 1 addition & 1 deletion docs/src/api/class-page.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# class: Page
* extends: [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter)
* extends: [EventEmitter]

Page provides methods to interact with a single tab in a [Browser], or an
[extension background page](https://developer.chrome.com/extensions/background_pages) in Chromium. One [Browser]
Expand Down
27 changes: 23 additions & 4 deletions docs/src/api/python.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,22 @@
## async method: Playwright.start
* langs: python

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.

```py
>>> from playwright.sync_api import sync_playwright

>>> playwright = sync_playwright().start()

>>> browser = playwright.chromium.launch()
>>> page = browser.newPage()
>>> page.goto("http://whatsmyuseragent.org/")
>>> page.screenshot(path="example.png")
>>> browser.close()

>>> playwright.stop()
```

## async method: Playwright.stop
* langs: python

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

```python async
async with page.expect_navigation():
await page.click("a.delayed-navigation") # Clicking the link will indirectly cause a navigation
await page.click("a.delayed-navigation") # Clicking the link will indirectly cause a navigation
# Context manager waited for the navigation to happen.
```

```python sync
with page.expect_navigation():
page.click("a.delayed-navigation") # Clicking the link will indirectly cause a navigation
page.click("a.delayed-navigation") # Clicking the link will indirectly cause a navigation
# Context manager waited for the navigation to happen.
```

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

```python async
async with frame.expect_navigation():
await frame.click("a.delayed-navigation") # Clicking the link will indirectly cause a navigation
await frame.click("a.delayed-navigation") # Clicking the link will indirectly cause a navigation
# Context manager waited for the navigation to happen.
```

```python sync
with frame.expect_navigation():
frame.click("a.delayed-navigation") # Clicking the link will indirectly cause a navigation
frame.click("a.delayed-navigation") # Clicking the link will indirectly cause a navigation
# Context manager waited for the navigation to happen.
```

Expand Down
2 changes: 1 addition & 1 deletion docs/src/assertions.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ title: "Assertions"
---

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
Node.js.
your script.

<!-- TOC -->

Expand Down
55 changes: 27 additions & 28 deletions docs/src/emulation.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,22 @@ title: "Device and environment emulation"
---

Playwright allows overriding various parameters of the device where the browser is running:
- viewport size, device scale factor, touch support
- locale, timezone
- color scheme
- geolocation
- viewport size, device scale factor, touch support
- locale, timezone
- color scheme
- geolocation

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.
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.

<!-- TOC -->

<br/>

## Devices

Playwright comes with a registry of device parameters for selected mobile devices. It can be used to simulate browser behavior on a mobile device:
Playwright comes with a registry of device parameters for selected mobile devices. It can be used to simulate browser
behavior on a mobile device:

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

async def main():
async with async_playwright() as p:
pixel_2 = p.devices['Pixel 2']
browser = await p.webkit.launch(headless=False)
context = await browser.new_context(
**pixel_2,
)
async def run(playwright):
pixel_2 = playwright.devices['Pixel 2']
browser = await playwright.webkit.launch(headless=False)
context = await browser.new_context(
**pixel_2,
)

asyncio.get_event_loop().run_until_complete(main())
async def main():
async with async_playwright() as playwright:
await run(playwright)
asyncio.run(main())
```

```python sync
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
pixel_2 = p.devices['Pixel 2']
browser = p.webkit.launch(headless=False)
def run(playwright):
pixel_2 = playwright.devices['Pixel 2']
browser = playwright.webkit.launch(headless=False)
context = browser.new_context(
**pixel_2,
)

with sync_playwright() as playwright:
run(playwright)
```

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

#### API reference

- [`property: Playwright.devices`]
- [`method: Browser.newContext`]

Expand Down Expand Up @@ -87,7 +93,6 @@ context = browser.new_context(
```

#### API reference

- [`method: Browser.newContext`]

<br/>
Expand Down Expand Up @@ -141,11 +146,9 @@ page.set_viewport_size(width=1600, height=1200)
context = browser.new_context(
viewport={ 'width': 2560, 'height': 1440 },
device_scale_factor=2,

```

#### API reference

- [`method: Browser.newContext`]
- [`method: Page.setViewportSize`]

Expand Down Expand Up @@ -178,7 +181,6 @@ context = browser.new_context(
```

#### API reference

- [`method: Browser.newContext`]

<br/>
Expand Down Expand Up @@ -248,14 +250,14 @@ context.clear_permissions()
```

#### API reference

- [`method: Browser.newContext`]
- [`method: BrowserContext.grantPermissions`]
- [`method: BrowserContext.clearPermissions`]

<br/>

## Geolocation

Create a context with `"geolocation"` permissions granted:

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

#### API reference

- [`method: Browser.newContext`]
- [`method: BrowserContext.setGeolocation`]

<br/>

## Color scheme and media

Create a context with dark or light mode. Pages created in this context will
follow this color scheme preference.
Create a context with dark or light mode. Pages created in this context will follow this color scheme preference.

```js
// Create context with dark mode
Expand Down Expand Up @@ -362,6 +362,5 @@ page.emulate_media(media='print')
```

#### API reference

- [`method: Browser.newContext`]
- [`method: Page.emulateMedia`]
- [`method: Page.emulateMedia`]
68 changes: 65 additions & 3 deletions docs/src/extensibility.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,20 @@ title: "Extensibility"
Playwright supports custom selector engines, registered with [`method: Selectors.register`].

Selector engine should have the following properties:

- `create` function to create a relative selector from `root` (root is either a `Document`, `ShadowRoot` or `Element`) to a `target` element.
- `create` function to create a relative selector from `root` (root is either a `Document`, `ShadowRoot` or `Element`)
to a `target` element.
- `query` function to query first element matching `selector` relative to the `root`.
- `queryAll` function to query all elements matching `selector` relative to the `root`.

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.
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.

An example of registering selector engine that queries elements based on a tag name:

```js
// Must be a function that evaluates to a selector engine instance.
const createTagNameEngine = () => ({
Expand All @@ -44,3 +50,59 @@ await page.click('tag=div >> span >> "Click me"');
// We can use it in any methods supporting selectors.
const buttonCount = await page.$$eval('tag=button', buttons => buttons.length);
```

```python async
tag_selector = """
// Must evaluate to a selector engine instance.
{
// Returns the first element matching given selector in the root's subtree.
query(root, selector) {
return root.querySelector(selector);
},

// Returns all elements matching given selector in the root's subtree.
queryAll(root, selector) {
return Array.from(root.querySelectorAll(selector));
}
}"""

# register the engine. selectors will be prefixed with "tag=".
await playwright.selectors.register("tag", tag_selector)

# now we can use "tag=" selectors.
button = await page.query_selector("tag=button")

# we can combine it with other selector engines using `>>` combinator.
await page.click("tag=div >> span >> "click me"")

# we can use it in any methods supporting selectors.
button_count = await page.eval_on_selector_all("tag=button", buttons => buttons.length)
```

```python sync
tag_selector = """
// Must evaluate to a selector engine instance.
{
// Returns the first element matching given selector in the root's subtree.
query(root, selector) {
return root.querySelector(selector);
},

// Returns all elements matching given selector in the root's subtree.
queryAll(root, selector) {
return Array.from(root.querySelectorAll(selector));
}
}"""

# register the engine. selectors will be prefixed with "tag=".
playwright.selectors.register("tag", tag_selector)

# now we can use "tag=" selectors.
button = page.query_selector("tag=button")

# we can combine it with other selector engines using `>>` combinator.
page.click("tag=div >> span >> "click me"")

# we can use it in any methods supporting selectors.
button_count = page.eval_on_selector_all("tag=button", buttons => buttons.length)
```
Loading