0
# Playwright
1
2
A comprehensive Python library for browser automation that provides a unified API for automating Chromium, Firefox, and WebKit browsers. Playwright enables reliable, fast, and ever-green automation with both synchronous and asynchronous execution models, supporting end-to-end testing, web scraping, and browser automation tasks with advanced features like auto-waiting, network interception, and mobile device emulation.
3
4
## Package Information
5
6
- **Package Name**: playwright
7
- **Language**: Python
8
- **Installation**: `pip install playwright`
9
- **Python Versions**: 3.9+
10
- **Browser Setup**: `playwright install` (downloads browser binaries)
11
12
## Core Imports
13
14
Synchronous API (recommended for most use cases):
15
16
```python
17
from playwright.sync_api import sync_playwright, Playwright, Browser, BrowserContext, Page, Locator, expect
18
```
19
20
Asynchronous API (for async/await patterns):
21
22
```python
23
from playwright.async_api import async_playwright, Playwright, Browser, BrowserContext, Page, Locator, expect
24
```
25
26
## Basic Usage
27
28
### Synchronous Browser Automation
29
30
```python
31
from playwright.sync_api import sync_playwright
32
33
# Launch browser and create page
34
with sync_playwright() as p:
35
browser = p.chromium.launch(headless=False)
36
page = browser.new_page()
37
38
# Navigate and interact with page
39
page.goto("https://example.com")
40
page.click("text=More information")
41
page.fill("#search-input", "automation")
42
page.press("#search-input", "Enter")
43
44
# Wait for and assert results
45
page.wait_for_selector(".search-results")
46
expect(page.locator(".search-results")).to_be_visible()
47
48
# Take screenshot
49
page.screenshot(path="results.png")
50
browser.close()
51
```
52
53
### Asynchronous Browser Automation
54
55
```python
56
import asyncio
57
from playwright.async_api import async_playwright
58
59
async def run():
60
async with async_playwright() as p:
61
browser = await p.chromium.launch()
62
page = await browser.new_page()
63
64
await page.goto("https://example.com")
65
await page.click("text=More information")
66
await page.fill("#search-input", "automation")
67
68
await browser.close()
69
70
asyncio.run(run())
71
```
72
73
## Architecture
74
75
Playwright follows a hierarchical architecture that mirrors browser organization:
76
77
- **Playwright**: Entry point providing access to browser types and global configuration
78
- **BrowserType**: Represents browser engines (Chromium, Firefox, WebKit) with launch capabilities
79
- **Browser**: Controls browser process, manages contexts and global settings
80
- **BrowserContext**: Isolated session with independent state (cookies, storage, permissions)
81
- **Page**: Individual browser tab with full automation capabilities
82
- **Frame**: Document frame within a page (main frame or iframe)
83
- **Locator**: Element finder with auto-waiting and retry logic
84
- **ElementHandle**: Direct reference to DOM elements (lower-level API)
85
86
This design enables reliable automation by providing isolation between sessions, automatic waiting for elements, and consistent cross-browser behavior.
87
88
## Capabilities
89
90
### Browser Management
91
92
Launch and control browser instances across Chromium, Firefox, and WebKit. Supports both headless and headed modes, custom browser configurations, persistent contexts with user data, and connection to remote browser instances.
93
94
```python { .api }
95
def sync_playwright() -> PlaywrightContextManager: ...
96
def async_playwright() -> PlaywrightContextManager: ...
97
98
class Playwright:
99
chromium: BrowserType
100
firefox: BrowserType
101
webkit: BrowserType
102
devices: Dict[str, Dict]
103
selectors: Selectors
104
request: APIRequest
105
106
class BrowserType:
107
def launch(**kwargs) -> Browser: ...
108
def launch_persistent_context(user_data_dir: str, **kwargs) -> BrowserContext: ...
109
def connect(ws_endpoint: str, **kwargs) -> Browser: ...
110
```
111
112
[Browser Management](./browser-management.md)
113
114
### Page Interaction
115
116
Navigate web pages, interact with elements, and manipulate page content. Includes navigation methods, element interaction, form handling, JavaScript execution, and page state management with comprehensive waiting strategies.
117
118
```python { .api }
119
class Page:
120
def goto(url: str, **kwargs) -> Optional[Response]: ...
121
def click(selector: str, **kwargs) -> None: ...
122
def fill(selector: str, value: str, **kwargs) -> None: ...
123
def type(selector: str, text: str, **kwargs) -> None: ...
124
def wait_for_selector(selector: str, **kwargs) -> Optional[ElementHandle]: ...
125
def screenshot(**kwargs) -> bytes: ...
126
def evaluate(expression: str, arg: Any = None) -> Any: ...
127
```
128
129
[Page Interaction](./page-interaction.md)
130
131
### Element Location and Interaction
132
133
Modern element location using Locator API with built-in auto-waiting, retry logic, and robust element interaction methods. Supports various locator strategies including text content, ARIA roles, labels, and CSS selectors.
134
135
```python { .api }
136
class Page:
137
def locator(selector: str) -> Locator: ...
138
def get_by_role(role: str, **kwargs) -> Locator: ...
139
def get_by_text(text: str, **kwargs) -> Locator: ...
140
def get_by_label(text: str, **kwargs) -> Locator: ...
141
def get_by_test_id(test_id: str) -> Locator: ...
142
143
class Locator:
144
def click(**kwargs) -> None: ...
145
def fill(value: str, **kwargs) -> None: ...
146
def is_visible(**kwargs) -> bool: ...
147
def wait_for(**kwargs) -> None: ...
148
def count() -> int: ...
149
```
150
151
[Element Location](./element-location.md)
152
153
### Network Interception
154
155
Intercept, modify, and mock network requests and responses. Enable testing of offline scenarios, API mocking, request/response modification, and comprehensive network monitoring for debugging and testing.
156
157
```python { .api }
158
class Page:
159
def route(url: Union[str, Pattern, Callable], handler: Callable) -> None: ...
160
def unroute(url: Union[str, Pattern, Callable], handler: Optional[Callable] = None) -> None: ...
161
162
class BrowserContext:
163
def route(url: Union[str, Pattern, Callable], handler: Callable) -> None: ...
164
def set_extra_http_headers(headers: Dict[str, str]) -> None: ...
165
166
class Route:
167
def abort(error_code: Optional[str] = None) -> None: ...
168
def continue_(**kwargs) -> None: ...
169
def fulfill(**kwargs) -> None: ...
170
```
171
172
[Network Interception](./network-interception.md)
173
174
### Assertions and Testing
175
176
Comprehensive assertion framework with built-in waiting and retry logic for reliable test automation. Supports page, element, and API response assertions with detailed error reporting and configurable timeouts.
177
178
```python { .api }
179
def expect(actual: Union[Page, Locator, APIResponse], message: Optional[str] = None) -> Union[PageAssertions, LocatorAssertions, APIResponseAssertions]: ...
180
181
class PageAssertions:
182
def to_have_title(title: Union[str, Pattern], **kwargs) -> None: ...
183
def to_have_url(url: Union[str, Pattern], **kwargs) -> None: ...
184
185
class LocatorAssertions:
186
def to_be_visible(**kwargs) -> None: ...
187
def to_have_text(expected: Union[str, Pattern, List], **kwargs) -> None: ...
188
def to_have_count(count: int, **kwargs) -> None: ...
189
def to_be_checked(**kwargs) -> None: ...
190
```
191
192
[Assertions](./assertions.md)
193
194
### API Testing
195
196
HTTP client for testing REST APIs and web services. Provides request/response handling, authentication, cookie management, and integration with browser contexts for end-to-end testing scenarios.
197
198
```python { .api }
199
class APIRequest:
200
def new_context(**kwargs) -> APIRequestContext: ...
201
202
class APIRequestContext:
203
def get(url: str, **kwargs) -> APIResponse: ...
204
def post(url: str, **kwargs) -> APIResponse: ...
205
def put(url: str, **kwargs) -> APIResponse: ...
206
def delete(url: str, **kwargs) -> APIResponse: ...
207
208
class APIResponse:
209
def json() -> Any: ...
210
def text() -> str: ...
211
def status: int
212
def ok: bool
213
```
214
215
[API Testing](./api-testing.md)
216
217
### Mobile and Device Emulation
218
219
Emulate mobile devices, tablets, and various screen configurations. Includes pre-configured device profiles, custom viewport settings, touch interaction, geolocation, and user agent configuration for comprehensive mobile testing.
220
221
```python { .api }
222
class BrowserContext:
223
def set_geolocation(geolocation: Optional[Dict]) -> None: ...
224
def grant_permissions(permissions: List[str], **kwargs) -> None: ...
225
226
class Page:
227
@property
228
def touchscreen() -> Touchscreen: ...
229
230
class Touchscreen:
231
def tap(x: float, y: float) -> None: ...
232
```
233
234
[Mobile Testing](./mobile-testing.md)
235
236
### Advanced Features
237
238
Specialized capabilities including WebSocket handling, video recording, accessibility testing, time manipulation, performance tracing, frame handling, and debugging tools for comprehensive browser automation testing.
239
240
```python { .api }
241
class WebSocket:
242
url: str
243
def wait_for_event(event: str, **kwargs) -> Any: ...
244
def is_closed() -> bool: ...
245
246
class Clock:
247
def fast_forward(ticks: Union[int, str]) -> None: ...
248
def install(time: Optional[Union[int, str, datetime.datetime]] = None) -> None: ...
249
def pause_at(time: Union[int, str, datetime.datetime]) -> None: ...
250
251
class Video:
252
def path() -> pathlib.Path: ...
253
def save_as(path: Union[str, pathlib.Path]) -> None: ...
254
255
class Accessibility:
256
def snapshot(root: Optional[ElementHandle] = None, **kwargs) -> Optional[Dict]: ...
257
```
258
259
[Advanced Features](./advanced-features.md)
260
261
## Data Structures
262
263
### Core Types
264
265
```python { .api }
266
# Geometry and positioning
267
class Position(TypedDict):
268
x: float
269
y: float
270
271
class FloatRect(TypedDict):
272
x: float
273
y: float
274
width: float
275
height: float
276
277
class ViewportSize(TypedDict):
278
width: int
279
height: int
280
281
# Browser configuration
282
class Geolocation(TypedDict):
283
latitude: float
284
longitude: float
285
accuracy: Optional[float]
286
287
class Cookie(TypedDict):
288
name: str
289
value: str
290
domain: str
291
path: str
292
expires: Optional[float]
293
httpOnly: Optional[bool]
294
secure: Optional[bool]
295
sameSite: Optional[str]
296
297
class HttpCredentials(TypedDict):
298
username: str
299
password: str
300
301
class ProxySettings(TypedDict):
302
server: str
303
bypass: Optional[str]
304
username: Optional[str]
305
password: Optional[str]
306
307
# Storage and session data
308
class StorageState(TypedDict):
309
cookies: List[Cookie]
310
origins: List[Dict]
311
312
class FilePayload(TypedDict):
313
name: str
314
mimeType: str
315
buffer: bytes
316
317
# Network and request data
318
class ResourceTiming(TypedDict):
319
startTime: float
320
domainLookupStart: float
321
domainLookupEnd: float
322
connectStart: float
323
connectEnd: float
324
secureConnectionStart: float
325
requestStart: float
326
responseStart: float
327
responseEnd: float
328
329
class RequestSizes(TypedDict):
330
requestBodySize: int
331
requestHeadersSize: int
332
responseBodySize: int
333
responseHeadersSize: int
334
335
class SourceLocation(TypedDict):
336
url: str
337
lineNumber: int
338
columnNumber: int
339
340
class RemoteAddr(TypedDict):
341
ipAddress: str
342
port: int
343
344
class SecurityDetails(TypedDict):
345
issuer: str
346
protocol: str
347
subjectName: str
348
validFrom: float
349
validTo: float
350
351
# PDF generation
352
class PdfMargins(TypedDict):
353
top: Optional[str]
354
bottom: Optional[str]
355
left: Optional[str]
356
right: Optional[str]
357
358
# Client certificates
359
class ClientCertificate(TypedDict):
360
origin: str
361
certPath: Optional[str]
362
keyPath: Optional[str]
363
passphrase: Optional[str]
364
pfxPath: Optional[str]
365
```
366
367
## Error Handling
368
369
```python { .api }
370
class Error(Exception):
371
"""Base exception for all Playwright errors."""
372
message: str
373
name: str
374
stack: str
375
376
class TimeoutError(Error):
377
"""Raised when operations exceed specified timeout."""
378
pass
379
```
380
381
Common error patterns:
382
- **TimeoutError**: Element not found, page load timeout, network timeout
383
- **Error**: Element not actionable, navigation failed, context closed
384
- Use try/except blocks around Playwright operations for robust error handling
385
- Configure timeouts via `timeout` parameter in methods and global `expect.set_options()`