0
# Advanced Features
1
2
Advanced Playwright capabilities including WebSocket handling, video recording, accessibility testing, time manipulation, debugging tools, and specialized browser features.
3
4
## Capabilities
5
6
### WebSocket Handling
7
8
Intercept and interact with WebSocket connections for real-time application testing.
9
10
```python { .api }
11
class WebSocket:
12
"""WebSocket connection handler."""
13
14
@property
15
def url(self) -> str:
16
"""WebSocket URL."""
17
18
def wait_for_event(
19
self,
20
event: str,
21
predicate: Optional[Callable] = None,
22
timeout: Optional[float] = None
23
) -> Any:
24
"""Wait for WebSocket event."""
25
26
def is_closed(self) -> bool:
27
"""Check if WebSocket is closed."""
28
29
class WebSocketRoute:
30
"""WebSocket route for message interception."""
31
32
def connect_to_server(self) -> None:
33
"""Connect route to the actual WebSocket server."""
34
35
def send(self, message: Union[str, bytes]) -> None:
36
"""Send message through WebSocket."""
37
38
def close(self, code: Optional[int] = None, reason: Optional[str] = None) -> None:
39
"""Close WebSocket connection."""
40
```
41
42
### Video Recording
43
44
Record browser sessions as video files for debugging and documentation.
45
46
```python { .api }
47
class Video:
48
"""Video recording handler."""
49
50
def path(self) -> pathlib.Path:
51
"""Get path to video file."""
52
53
def save_as(self, path: Union[str, pathlib.Path]) -> None:
54
"""Save video to specified path."""
55
56
def delete(self) -> None:
57
"""Delete video file."""
58
```
59
60
### Web Workers
61
62
Handle Web Worker threads in browser pages.
63
64
```python { .api }
65
class Worker:
66
"""Web Worker handler."""
67
68
@property
69
def url(self) -> str:
70
"""Worker script URL."""
71
72
def evaluate(self, expression: str, arg: Any = None) -> Any:
73
"""Execute JavaScript in worker context."""
74
75
def evaluate_handle(self, expression: str, arg: Any = None) -> JSHandle:
76
"""Execute JavaScript and return handle."""
77
```
78
79
### Console Messages
80
81
Capture and analyze browser console output.
82
83
```python { .api }
84
class ConsoleMessage:
85
"""Browser console message."""
86
87
@property
88
def type(self) -> str:
89
"""Message type: 'log', 'debug', 'info', 'error', 'warning', 'dir', etc."""
90
91
@property
92
def text(self) -> str:
93
"""Console message text."""
94
95
@property
96
def args(self) -> List[JSHandle]:
97
"""Message arguments as JavaScript handles."""
98
99
@property
100
def location(self) -> Dict:
101
"""Source location information."""
102
```
103
104
### Accessibility Testing
105
106
Access browser accessibility tree for automated accessibility testing.
107
108
```python { .api }
109
class Accessibility:
110
"""Accessibility tree access."""
111
112
def snapshot(
113
self,
114
root: Optional[ElementHandle] = None,
115
interesting_only: Optional[bool] = None
116
) -> Optional[Dict]:
117
"""
118
Capture accessibility tree snapshot.
119
120
Args:
121
root: Root element (defaults to page root)
122
interesting_only: Filter to only interesting nodes
123
124
Returns:
125
Dict: Accessibility tree data
126
"""
127
```
128
129
### Time Manipulation
130
131
Control browser time for consistent testing of time-dependent functionality.
132
133
```python { .api }
134
class Clock:
135
"""Browser time manipulation."""
136
137
def fast_forward(self, ticks: Union[int, str]) -> None:
138
"""Advance time by specified amount."""
139
140
def install(self, time: Optional[Union[int, str, datetime.datetime]] = None) -> None:
141
"""Install fake timer at specified time."""
142
143
def pause_at(self, time: Union[int, str, datetime.datetime]) -> None:
144
"""Pause time at specific moment."""
145
146
def resume(self) -> None:
147
"""Resume normal time flow."""
148
149
def run_for(self, ticks: Union[int, str]) -> None:
150
"""Run time for specified duration."""
151
152
def set_fixed_time(self, time: Union[int, str, datetime.datetime]) -> None:
153
"""Set fixed time that doesn't advance."""
154
155
def set_system_time(self, time: Union[int, str, datetime.datetime]) -> None:
156
"""Set system time."""
157
```
158
159
### Performance Tracing
160
161
Capture performance traces for analysis and debugging.
162
163
```python { .api }
164
class Tracing:
165
"""Performance tracing capabilities."""
166
167
def start(
168
self,
169
name: Optional[str] = None,
170
title: Optional[str] = None,
171
screenshots: Optional[bool] = None,
172
snapshots: Optional[bool] = None,
173
sources: Optional[bool] = None
174
) -> None:
175
"""Start recording trace."""
176
177
def start_chunk(
178
self,
179
name: Optional[str] = None,
180
title: Optional[str] = None
181
) -> None:
182
"""Start new trace chunk."""
183
184
def stop_chunk(self, path: Optional[Union[str, pathlib.Path]] = None) -> None:
185
"""Stop current trace chunk."""
186
187
def stop(self, path: Optional[Union[str, pathlib.Path]] = None) -> None:
188
"""Stop tracing and save to file."""
189
```
190
191
### Frame Handling
192
193
Navigate and interact with iframes and nested frames.
194
195
```python { .api }
196
class Frame:
197
"""Browser frame (main frame or iframe)."""
198
199
@property
200
def name(self) -> str:
201
"""Frame name attribute."""
202
203
@property
204
def url(self) -> str:
205
"""Frame URL."""
206
207
@property
208
def parent_frame(self) -> Optional[Frame]:
209
"""Parent frame (None for main frame)."""
210
211
@property
212
def child_frames(self) -> List[Frame]:
213
"""List of child frames."""
214
215
def locator(self, selector: str) -> Locator:
216
"""Create locator within this frame."""
217
218
def goto(self, url: str, **kwargs) -> Optional[Response]:
219
"""Navigate frame to URL."""
220
221
def evaluate(self, expression: str, arg: Any = None) -> Any:
222
"""Execute JavaScript in frame context."""
223
224
class FrameLocator:
225
"""Locator for elements within iframes."""
226
227
def locator(self, selector: str) -> FrameLocator:
228
"""Create nested locator within frame."""
229
230
def first(self) -> FrameLocator:
231
"""First matching frame."""
232
233
def last(self) -> FrameLocator:
234
"""Last matching frame."""
235
236
def nth(self, index: int) -> FrameLocator:
237
"""Frame at specific index."""
238
```
239
240
### Error Handling
241
242
Handle web errors and browser-specific error conditions.
243
244
```python { .api }
245
class WebError:
246
"""Web error information."""
247
248
@property
249
def text(self) -> Optional[str]:
250
"""Error text description."""
251
```
252
253
### CSS Selectors
254
255
Advanced selector registration and custom selector engines.
256
257
```python { .api }
258
class Selectors:
259
"""CSS selector engine management."""
260
261
def register(
262
self,
263
name: str,
264
script: str,
265
content_script: Optional[bool] = None
266
) -> None:
267
"""Register custom selector engine."""
268
269
def set_test_id_attribute(self, attribute_name: str) -> None:
270
"""Set attribute name for test ID selectors."""
271
```
272
273
Usage examples:
274
275
```python
276
# WebSocket interception
277
def handle_websocket(ws):
278
print(f"WebSocket opened: {ws.url}")
279
ws.on("framereceived", lambda payload: print(f"Received: {payload}"))
280
281
page.on("websocket", handle_websocket)
282
283
# Video recording
284
context = browser.new_context(record_video_dir="./videos")
285
page = context.new_page()
286
# ... perform actions ...
287
video = page.video
288
video.save_as("./test-recording.webm")
289
290
# Accessibility testing
291
accessibility_tree = page.accessibility.snapshot()
292
print(f"Page has {len(accessibility_tree.get('children', []))} accessible elements")
293
294
# Time manipulation
295
page.clock.install()
296
page.clock.pause_at("2024-01-01")
297
page.goto("https://example.com") # Page sees fixed time
298
299
# Frame handling
300
frame = page.frame_locator("iframe").first()
301
frame.locator("button").click()
302
```