pure-patchright 1.62.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. patchright/__init__.py +5 -0
  2. patchright/__main__.py +18 -0
  3. patchright/_impl/__init__.py +0 -0
  4. patchright/_impl/__pyinstaller/__init__.py +20 -0
  5. patchright/_impl/__pyinstaller/hook-playwright.async_api.py +3 -0
  6. patchright/_impl/__pyinstaller/hook-playwright.sync_api.py +3 -0
  7. patchright/_impl/_api_structures.py +343 -0
  8. patchright/_impl/_artifact.py +46 -0
  9. patchright/_impl/_assertions.py +1014 -0
  10. patchright/_impl/_async_base.py +88 -0
  11. patchright/_impl/_browser.py +267 -0
  12. patchright/_impl/_browser_context.py +759 -0
  13. patchright/_impl/_browser_type.py +336 -0
  14. patchright/_impl/_cdp_session.py +25 -0
  15. patchright/_impl/_clock.py +62 -0
  16. patchright/_impl/_connection.py +686 -0
  17. patchright/_impl/_console_message.py +83 -0
  18. patchright/_impl/_credentials.py +38 -0
  19. patchright/_impl/_debugger.py +37 -0
  20. patchright/_impl/_dialog.py +45 -0
  21. patchright/_impl/_disposable.py +71 -0
  22. patchright/_impl/_download.py +49 -0
  23. patchright/_impl/_driver.py +24 -0
  24. patchright/_impl/_element_handle.py +446 -0
  25. patchright/_impl/_errors.py +46 -0
  26. patchright/_impl/_event_context_manager.py +19 -0
  27. patchright/_impl/_fetch.py +592 -0
  28. patchright/_impl/_file_chooser.py +42 -0
  29. patchright/_impl/_form_data.py +19 -0
  30. patchright/_impl/_frame.py +959 -0
  31. patchright/_impl/_glob.py +47 -0
  32. patchright/_impl/_greenlets.py +35 -0
  33. patchright/_impl/_har_router.py +98 -0
  34. patchright/_impl/_helper.py +551 -0
  35. patchright/_impl/_impl_to_api_mapping.py +141 -0
  36. patchright/_impl/_input.py +85 -0
  37. patchright/_impl/_js_handle.py +297 -0
  38. patchright/_impl/_json_pipe.py +55 -0
  39. patchright/_impl/_local_utils.py +73 -0
  40. patchright/_impl/_locator.py +894 -0
  41. patchright/_impl/_map.py +18 -0
  42. patchright/_impl/_network.py +953 -0
  43. patchright/_impl/_object_factory.py +93 -0
  44. patchright/_impl/_page.py +1601 -0
  45. patchright/_impl/_path_utils.py +13 -0
  46. patchright/_impl/_playwright.py +43 -0
  47. patchright/_impl/_screencast.py +149 -0
  48. patchright/_impl/_selectors.py +48 -0
  49. patchright/_impl/_set_input_files_helpers.py +134 -0
  50. patchright/_impl/_str_utils.py +59 -0
  51. patchright/_impl/_stream.py +31 -0
  52. patchright/_impl/_sync_base.py +130 -0
  53. patchright/_impl/_tracing.py +243 -0
  54. patchright/_impl/_transport.py +151 -0
  55. patchright/_impl/_video.py +41 -0
  56. patchright/_impl/_waiter.py +168 -0
  57. patchright/_impl/_web_error.py +33 -0
  58. patchright/_impl/_web_storage.py +41 -0
  59. patchright/_impl/_writable_stream.py +26 -0
  60. patchright/_repo_version.py +1 -0
  61. patchright/async_api/__init__.py +234 -0
  62. patchright/async_api/_context_manager.py +38 -0
  63. patchright/async_api/_generated.py +23396 -0
  64. patchright/driver/README.md +1 -0
  65. patchright/driver/package/README.md +3 -0
  66. patchright/driver/package/ThirdPartyNotices.txt +13 -0
  67. patchright/driver/package/bin/install_media_pack.ps1 +5 -0
  68. patchright/driver/package/bin/install_webkit_wsl.ps1 +33 -0
  69. patchright/driver/package/bin/reinstall_chrome_beta_linux.sh +42 -0
  70. patchright/driver/package/bin/reinstall_chrome_beta_mac.sh +13 -0
  71. patchright/driver/package/bin/reinstall_chrome_beta_win.ps1 +24 -0
  72. patchright/driver/package/bin/reinstall_chrome_stable_linux.sh +42 -0
  73. patchright/driver/package/bin/reinstall_chrome_stable_mac.sh +12 -0
  74. patchright/driver/package/bin/reinstall_chrome_stable_win.ps1 +24 -0
  75. patchright/driver/package/bin/reinstall_msedge_beta_linux.sh +48 -0
  76. patchright/driver/package/bin/reinstall_msedge_beta_mac.sh +11 -0
  77. patchright/driver/package/bin/reinstall_msedge_beta_win.ps1 +23 -0
  78. patchright/driver/package/bin/reinstall_msedge_dev_linux.sh +48 -0
  79. patchright/driver/package/bin/reinstall_msedge_dev_mac.sh +11 -0
  80. patchright/driver/package/bin/reinstall_msedge_dev_win.ps1 +23 -0
  81. patchright/driver/package/bin/reinstall_msedge_stable_linux.sh +48 -0
  82. patchright/driver/package/bin/reinstall_msedge_stable_mac.sh +11 -0
  83. patchright/driver/package/bin/reinstall_msedge_stable_win.ps1 +24 -0
  84. patchright/driver/package/browsers.json +75 -0
  85. patchright/driver/package/cli.js +21 -0
  86. patchright/driver/package/index.js +17 -0
  87. patchright/driver/package/index.mjs +28 -0
  88. patchright/driver/package/lib/bootstrap.js +88 -0
  89. patchright/driver/package/lib/coreBundle.js +77498 -0
  90. patchright/driver/package/lib/entry/cliDaemon.js +5 -0
  91. patchright/driver/package/lib/entry/dashboardApp.js +3 -0
  92. patchright/driver/package/lib/entry/mcp.js +10 -0
  93. patchright/driver/package/lib/entry/oopBrowserDownload.js +3 -0
  94. patchright/driver/package/lib/package.js +50 -0
  95. patchright/driver/package/lib/server/chromium/appIcon.png +0 -0
  96. patchright/driver/package/lib/server/electron/loader.js +107 -0
  97. patchright/driver/package/lib/serverRegistry.js +7347 -0
  98. patchright/driver/package/lib/serverRegistry.js.LICENSE +354 -0
  99. patchright/driver/package/lib/tools/cli-client/channelSessions.js +141 -0
  100. patchright/driver/package/lib/tools/cli-client/cli.js +6 -0
  101. patchright/driver/package/lib/tools/cli-client/help.json +708 -0
  102. patchright/driver/package/lib/tools/cli-client/minimist.js +128 -0
  103. patchright/driver/package/lib/tools/cli-client/output.js +343 -0
  104. patchright/driver/package/lib/tools/cli-client/program.js +404 -0
  105. patchright/driver/package/lib/tools/cli-client/registry.js +176 -0
  106. patchright/driver/package/lib/tools/cli-client/session.js +258 -0
  107. patchright/driver/package/lib/tools/dashboard/appIcon.png +0 -0
  108. patchright/driver/package/lib/tools/skills/playwright-cli/SKILL.md +420 -0
  109. patchright/driver/package/lib/tools/skills/playwright-cli/references/element-attributes.md +23 -0
  110. patchright/driver/package/lib/tools/skills/playwright-cli/references/playwright-tests.md +39 -0
  111. patchright/driver/package/lib/tools/skills/playwright-cli/references/request-mocking.md +87 -0
  112. patchright/driver/package/lib/tools/skills/playwright-cli/references/running-code.md +241 -0
  113. patchright/driver/package/lib/tools/skills/playwright-cli/references/session-management.md +225 -0
  114. patchright/driver/package/lib/tools/skills/playwright-cli/references/storage-state.md +275 -0
  115. patchright/driver/package/lib/tools/skills/playwright-cli/references/test-generation.md +433 -0
  116. patchright/driver/package/lib/tools/skills/playwright-cli/references/tracing.md +139 -0
  117. patchright/driver/package/lib/tools/skills/playwright-cli/references/video-recording.md +143 -0
  118. patchright/driver/package/lib/tools/skills/playwright-component-testing/SKILL.md +143 -0
  119. patchright/driver/package/lib/tools/skills/playwright-component-testing/references/gallery-spec.md +144 -0
  120. patchright/driver/package/lib/tools/skills/playwright-component-testing/references/migration.md +85 -0
  121. patchright/driver/package/lib/tools/skills/playwright-component-testing/references/react.md +67 -0
  122. patchright/driver/package/lib/tools/skills/playwright-component-testing/references/vue.md +75 -0
  123. patchright/driver/package/lib/tools/skills/playwright-trace/SKILL.md +171 -0
  124. patchright/driver/package/lib/tools/utils/extension.js +101 -0
  125. patchright/driver/package/lib/tools/utils/socketConnection.js +108 -0
  126. patchright/driver/package/lib/utilsBundle.js +90764 -0
  127. patchright/driver/package/lib/utilsBundle.js.LICENSE +2179 -0
  128. patchright/driver/package/lib/webp_codec.LICENSE +173 -0
  129. patchright/driver/package/lib/webp_codec.wasm +0 -0
  130. patchright/driver/package/lib/xdg-open +1267 -0
  131. patchright/driver/package/package.json +34 -0
  132. patchright/py.typed +0 -0
  133. patchright/sync_api/__init__.py +234 -0
  134. patchright/sync_api/_context_manager.py +73 -0
  135. patchright/sync_api/_generated.py +23590 -0
  136. pure_patchright-1.62.3.dist-info/LICENSE +201 -0
  137. pure_patchright-1.62.3.dist-info/METADATA +96 -0
  138. pure_patchright-1.62.3.dist-info/RECORD +142 -0
  139. pure_patchright-1.62.3.dist-info/WHEEL +4 -0
  140. pure_patchright-1.62.3.dist-info/entry_points.txt +5 -0
  141. pure_patchright-1.62.3.dist-info/licenses/LICENSE +202 -0
  142. pure_patchright-1.62.3.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1601 @@
1
+ import asyncio
2
+ import base64
3
+ import inspect
4
+ import re
5
+ import sys
6
+ from pathlib import Path
7
+ from types import SimpleNamespace
8
+ from typing import (
9
+ TYPE_CHECKING,
10
+ Any,
11
+ Awaitable,
12
+ Callable,
13
+ Dict,
14
+ List,
15
+ Literal,
16
+ Optional,
17
+ Pattern,
18
+ Sequence,
19
+ Union,
20
+ cast,
21
+ )
22
+ from patchright._impl._api_structures import (
23
+ AriaRole,
24
+ FilePayload,
25
+ FloatRect,
26
+ PdfMargins,
27
+ Position,
28
+ ViewportSize,
29
+ )
30
+ from patchright._impl._artifact import Artifact
31
+ from patchright._impl._clock import Clock
32
+ from patchright._impl._connection import (
33
+ ChannelOwner,
34
+ from_channel,
35
+ from_nullable_channel,
36
+ )
37
+ from patchright._impl._console_message import ConsoleMessage
38
+ from patchright._impl._disposable import Disposable, DisposableStub
39
+ from patchright._impl._download import Download
40
+ from patchright._impl._element_handle import ElementHandle, determine_screenshot_type
41
+ from patchright._impl._errors import Error, TargetClosedError, is_target_closed_error
42
+ from patchright._impl._event_context_manager import EventContextManagerImpl
43
+ from patchright._impl._file_chooser import FileChooser
44
+ from patchright._impl._frame import Frame
45
+ from patchright._impl._greenlets import LocatorHandlerGreenlet
46
+ from patchright._impl._har_router import HarRouter
47
+ from patchright._impl._helper import (
48
+ ColorScheme,
49
+ Contrast,
50
+ DocumentLoadState,
51
+ ForcedColors,
52
+ HarMode,
53
+ KeyboardModifier,
54
+ MouseButton,
55
+ ReducedMotion,
56
+ RouteFromHarNotFoundPolicy,
57
+ RouteHandler,
58
+ RouteHandlerCallback,
59
+ TimeoutSettings,
60
+ URLMatch,
61
+ URLMatchRequest,
62
+ URLMatchResponse,
63
+ WebSocketRouteHandlerCallback,
64
+ async_readfile,
65
+ async_writefile,
66
+ locals_to_params,
67
+ make_dirs_for_file,
68
+ parse_error,
69
+ serialize_error,
70
+ url_matches,
71
+ )
72
+ from patchright._impl._input import Keyboard, Mouse, Touchscreen
73
+ from patchright._impl._js_handle import (
74
+ JSHandle,
75
+ Serializable,
76
+ add_source_url_to_script,
77
+ parse_result,
78
+ serialize_argument,
79
+ )
80
+ from patchright._impl._network import (
81
+ Request,
82
+ Response,
83
+ Route,
84
+ WebSocketRoute,
85
+ WebSocketRouteHandler,
86
+ serialize_headers,
87
+ )
88
+ from patchright._impl._screencast import Screencast
89
+ from patchright._impl._video import Video
90
+ from patchright._impl._waiter import Waiter
91
+ from patchright._impl._web_storage import WebStorage
92
+
93
+ if TYPE_CHECKING:
94
+ from patchright._impl._browser_context import BrowserContext
95
+ from patchright._impl._fetch import APIRequestContext
96
+ from patchright._impl._locator import FrameLocator, Locator
97
+ from patchright._impl._network import WebSocket
98
+
99
+
100
+ class LocatorHandler:
101
+ locator: "Locator"
102
+ handler: Union[Callable[["Locator"], Any], Callable[..., Any]]
103
+ times: Union[int, None]
104
+
105
+ def __init__(
106
+ self, locator: "Locator", handler: Callable[..., Any], times: Union[int, None]
107
+ ) -> None:
108
+ self.locator = locator
109
+ self._handler = handler
110
+ self.times = times
111
+
112
+ def __call__(self) -> Any:
113
+ arg_count = len(inspect.signature(self._handler).parameters)
114
+ if arg_count == 0:
115
+ return self._handler()
116
+ return self._handler(self.locator)
117
+
118
+
119
+ class Page(ChannelOwner):
120
+ Events = SimpleNamespace(
121
+ Close="close",
122
+ Crash="crash",
123
+ Console="console",
124
+ Dialog="dialog",
125
+ Download="download",
126
+ FileChooser="filechooser",
127
+ DOMContentLoaded="domcontentloaded",
128
+ PageError="pageerror",
129
+ Request="request",
130
+ Response="response",
131
+ RequestFailed="requestfailed",
132
+ RequestFinished="requestfinished",
133
+ FrameAttached="frameattached",
134
+ FrameDetached="framedetached",
135
+ FrameNavigated="framenavigated",
136
+ Load="load",
137
+ Popup="popup",
138
+ WebSocket="websocket",
139
+ Worker="worker",
140
+ )
141
+ keyboard: Keyboard
142
+ mouse: Mouse
143
+ touchscreen: Touchscreen
144
+
145
+ def __init__(
146
+ self, parent: ChannelOwner, type: str, guid: str, initializer: Dict
147
+ ) -> None:
148
+ super().__init__(parent, type, guid, initializer)
149
+ self._browser_context = cast("BrowserContext", parent)
150
+ self.keyboard = Keyboard(self._channel)
151
+ self.mouse = Mouse(self._channel)
152
+ self.touchscreen = Touchscreen(self._channel)
153
+ self._main_frame: Frame = from_channel(initializer["mainFrame"])
154
+ self._main_frame._page = self
155
+ self._frames = [self._main_frame]
156
+ self._viewport_size: Optional[ViewportSize] = initializer.get("viewportSize")
157
+ self._is_closed = False
158
+ self._workers: List["Worker"] = []
159
+ self._bindings: Dict[str, Any] = {}
160
+ self._routes: List[RouteHandler] = []
161
+ self._web_socket_routes: List[WebSocketRouteHandler] = []
162
+ self._owned_context: Optional["BrowserContext"] = None
163
+ self._timeout_settings: TimeoutSettings = TimeoutSettings(
164
+ self._browser_context._timeout_settings
165
+ )
166
+ self._video: Video = Video(
167
+ self,
168
+ cast(Optional[Artifact], from_nullable_channel(initializer.get("video"))),
169
+ )
170
+ self._screencast: Screencast = Screencast(self)
171
+ self._local_storage = WebStorage(self, "local")
172
+ self._session_storage = WebStorage(self, "session")
173
+ self._opener = cast("Page", from_nullable_channel(initializer.get("opener")))
174
+ self._close_reason: Optional[str] = None
175
+ self._close_was_called = False
176
+ self._har_routers: List[HarRouter] = []
177
+ self._locator_handlers: Dict[str, LocatorHandler] = {}
178
+ self._channel.on(
179
+ "bindingCall",
180
+ lambda params: self._on_binding(from_channel(params["binding"])),
181
+ )
182
+ self._channel.on("close", lambda _: self._on_close())
183
+ self._channel.on("crash", lambda _: self._on_crash())
184
+ self._channel.on("download", lambda params: self._on_download(params))
185
+ self._channel.on(
186
+ "fileChooser",
187
+ lambda params: self.emit(
188
+ Page.Events.FileChooser,
189
+ FileChooser(
190
+ self, from_channel(params["element"]), params["isMultiple"]
191
+ ),
192
+ ),
193
+ )
194
+ self._channel.on(
195
+ "frameAttached",
196
+ lambda params: self._on_frame_attached(from_channel(params["frame"])),
197
+ )
198
+ self._channel.on(
199
+ "frameDetached",
200
+ lambda params: self._on_frame_detached(from_channel(params["frame"])),
201
+ )
202
+ self._channel.on(
203
+ "locatorHandlerTriggered",
204
+ lambda params: self._loop.create_task(
205
+ self._on_locator_handler_triggered(params["uid"])
206
+ ),
207
+ )
208
+ self._channel.on(
209
+ "route",
210
+ lambda params: self._loop.create_task(
211
+ self._on_route(from_channel(params["route"]))
212
+ ),
213
+ )
214
+ self._channel.on(
215
+ "webSocketRoute",
216
+ lambda params: self._loop.create_task(
217
+ self._on_web_socket_route(from_channel(params["webSocketRoute"]))
218
+ ),
219
+ )
220
+ self._channel.on("viewportSizeChanged", self._on_viewport_size_changed)
221
+ self._channel.on(
222
+ "webSocket",
223
+ lambda params: self.emit(
224
+ Page.Events.WebSocket, from_channel(params["webSocket"])
225
+ ),
226
+ )
227
+ self._channel.on(
228
+ "worker", lambda params: self._on_worker(from_channel(params["worker"]))
229
+ )
230
+ self._closed_or_crashed_future: asyncio.Future = asyncio.Future()
231
+ self.on(
232
+ Page.Events.Close,
233
+ lambda _: (
234
+ self._closed_or_crashed_future.set_result(
235
+ self._close_error_with_reason()
236
+ )
237
+ if not self._closed_or_crashed_future.done()
238
+ else None
239
+ ),
240
+ )
241
+ self.on(
242
+ Page.Events.Crash,
243
+ lambda _: (
244
+ self._closed_or_crashed_future.set_result(TargetClosedError())
245
+ if not self._closed_or_crashed_future.done()
246
+ else None
247
+ ),
248
+ )
249
+ self._set_event_to_subscription_mapping(
250
+ {
251
+ Page.Events.Console: "console",
252
+ Page.Events.Dialog: "dialog",
253
+ Page.Events.Request: "request",
254
+ Page.Events.Response: "response",
255
+ Page.Events.RequestFinished: "requestFinished",
256
+ Page.Events.RequestFailed: "requestFailed",
257
+ Page.Events.FileChooser: "fileChooser",
258
+ }
259
+ )
260
+
261
+ def __repr__(self) -> str:
262
+ return f"<Page url={self.url!r}>"
263
+
264
+ def _on_frame_attached(self, frame: Frame) -> None:
265
+ frame._page = self
266
+ self._frames.append(frame)
267
+ self.emit(Page.Events.FrameAttached, frame)
268
+ self._browser_context.emit("frameattached", frame)
269
+
270
+ def _on_frame_detached(self, frame: Frame) -> None:
271
+ self._frames.remove(frame)
272
+ frame._detached = True
273
+ self.emit(Page.Events.FrameDetached, frame)
274
+ self._browser_context.emit("framedetached", frame)
275
+
276
+ async def _on_route(self, route: Route) -> None:
277
+ route._context = self.context
278
+ route_handlers = self._routes.copy()
279
+ for route_handler in route_handlers:
280
+ if self._close_was_called or self.context._closing_or_closed:
281
+ return
282
+ if not route_handler.matches(route.request.url):
283
+ continue
284
+ if route_handler not in self._routes:
285
+ continue
286
+ if route_handler.will_expire:
287
+ self._routes.remove(route_handler)
288
+ try:
289
+ handled = await route_handler.handle(route)
290
+ finally:
291
+ if len(self._routes) == 0:
292
+
293
+ async def _update_interceptor_patterns_ignore_exceptions() -> None:
294
+ try:
295
+ await self._update_interception_patterns()
296
+ except Error:
297
+ pass
298
+
299
+ asyncio.create_task(
300
+ self._connection.wrap_api_call(
301
+ _update_interceptor_patterns_ignore_exceptions, True
302
+ )
303
+ )
304
+ if handled:
305
+ return
306
+ await self._browser_context._on_route(route)
307
+
308
+ async def _on_web_socket_route(self, web_socket_route: WebSocketRoute) -> None:
309
+ route_handler = next(
310
+ (
311
+ route_handler
312
+ for route_handler in self._web_socket_routes
313
+ if route_handler.matches(web_socket_route.url)
314
+ ),
315
+ None,
316
+ )
317
+ if route_handler:
318
+ await route_handler.handle(web_socket_route)
319
+ else:
320
+ await self._browser_context._on_web_socket_route(web_socket_route)
321
+
322
+ def _on_binding(self, binding_call: "BindingCall") -> None:
323
+ func = self._bindings.get(binding_call._initializer["name"])
324
+ if func:
325
+ asyncio.create_task(binding_call.call(func))
326
+ self._browser_context._on_binding(binding_call)
327
+
328
+ def _on_worker(self, worker: "Worker") -> None:
329
+ self._workers.append(worker)
330
+ worker._page = self
331
+ self.emit(Page.Events.Worker, worker)
332
+
333
+ def _on_close(self) -> None:
334
+ self._is_closed = True
335
+ if self in self._browser_context._pages:
336
+ self._browser_context._pages.remove(self)
337
+ self._dispose_har_routers()
338
+ self.emit(Page.Events.Close, self)
339
+ self._browser_context.emit("pageclose", self)
340
+
341
+ def _on_crash(self) -> None:
342
+ self.emit(Page.Events.Crash, self)
343
+
344
+ def _on_download(self, params: Any) -> None:
345
+ url = params["url"]
346
+ suggested_filename = params["suggestedFilename"]
347
+ artifact = cast(Artifact, from_channel(params["artifact"]))
348
+ download = Download(self, url, suggested_filename, artifact)
349
+ self.emit(Page.Events.Download, download)
350
+ self._browser_context.emit("download", download)
351
+
352
+ def _on_viewport_size_changed(self, params: Any) -> None:
353
+ self._viewport_size = params["viewportSize"]
354
+
355
+ @property
356
+ def context(self) -> "BrowserContext":
357
+ return self._browser_context
358
+
359
+ @property
360
+ def clock(self) -> Clock:
361
+ return self._browser_context.clock
362
+
363
+ async def opener(self) -> Optional["Page"]:
364
+ if self._opener and self._opener.is_closed():
365
+ return None
366
+ return self._opener
367
+
368
+ @property
369
+ def main_frame(self) -> Frame:
370
+ return self._main_frame
371
+
372
+ def frame(self, name: str = None, url: URLMatch = None) -> Optional[Frame]:
373
+ for frame in self._frames:
374
+ if name and frame.name == name:
375
+ return frame
376
+ if url and url_matches(self._browser_context._base_url, frame.url, url):
377
+ return frame
378
+ return None
379
+
380
+ @property
381
+ def frames(self) -> List[Frame]:
382
+ return self._frames.copy()
383
+
384
+ def set_default_navigation_timeout(self, timeout: float) -> None:
385
+ self._timeout_settings.set_default_navigation_timeout(timeout)
386
+
387
+ def set_default_timeout(self, timeout: float) -> None:
388
+ self._timeout_settings.set_default_timeout(timeout)
389
+
390
+ async def query_selector(
391
+ self, selector: str, strict: bool = None
392
+ ) -> Optional[ElementHandle]:
393
+ return await self._main_frame.query_selector(selector, strict)
394
+
395
+ async def query_selector_all(self, selector: str) -> List[ElementHandle]:
396
+ return await self._main_frame.query_selector_all(selector)
397
+
398
+ async def wait_for_selector(
399
+ self,
400
+ selector: str,
401
+ timeout: float = None,
402
+ state: Literal["attached", "detached", "hidden", "visible"] = None,
403
+ strict: bool = None,
404
+ ) -> Optional[ElementHandle]:
405
+ return await self._main_frame.wait_for_selector(**locals_to_params(locals()))
406
+
407
+ async def is_checked(
408
+ self, selector: str, strict: bool = None, timeout: float = None
409
+ ) -> bool:
410
+ return await self._main_frame.is_checked(**locals_to_params(locals()))
411
+
412
+ async def is_disabled(
413
+ self, selector: str, strict: bool = None, timeout: float = None
414
+ ) -> bool:
415
+ return await self._main_frame.is_disabled(**locals_to_params(locals()))
416
+
417
+ async def is_editable(
418
+ self, selector: str, strict: bool = None, timeout: float = None
419
+ ) -> bool:
420
+ return await self._main_frame.is_editable(**locals_to_params(locals()))
421
+
422
+ async def is_enabled(
423
+ self, selector: str, strict: bool = None, timeout: float = None
424
+ ) -> bool:
425
+ return await self._main_frame.is_enabled(**locals_to_params(locals()))
426
+
427
+ async def is_hidden(
428
+ self, selector: str, strict: bool = None, timeout: float = None
429
+ ) -> bool:
430
+ return await self._main_frame.is_hidden(selector=selector, strict=strict)
431
+
432
+ async def is_visible(
433
+ self, selector: str, strict: bool = None, timeout: float = None
434
+ ) -> bool:
435
+ return await self._main_frame.is_visible(selector=selector, strict=strict)
436
+
437
+ async def dispatch_event(
438
+ self,
439
+ selector: str,
440
+ type: str,
441
+ eventInit: Dict = None,
442
+ timeout: float = None,
443
+ strict: bool = None,
444
+ ) -> None:
445
+ return await self._main_frame.dispatch_event(**locals_to_params(locals()))
446
+
447
+ async def evaluate(
448
+ self,
449
+ expression: str,
450
+ arg: Serializable = None,
451
+ *,
452
+ isolatedContext: Optional[bool] = True,
453
+ ) -> Any:
454
+ return await self._main_frame.evaluate(
455
+ expression, arg, isolatedContext=isolatedContext
456
+ )
457
+
458
+ async def evaluate_handle(
459
+ self,
460
+ expression: str,
461
+ arg: Serializable = None,
462
+ *,
463
+ isolatedContext: Optional[bool] = True,
464
+ ) -> JSHandle:
465
+ return await self._main_frame.evaluate_handle(
466
+ expression, arg, isolatedContext=isolatedContext
467
+ )
468
+
469
+ async def eval_on_selector(
470
+ self,
471
+ selector: str,
472
+ expression: str,
473
+ arg: Serializable = None,
474
+ strict: bool = None,
475
+ ) -> Any:
476
+ return await self._main_frame.eval_on_selector(
477
+ selector, expression, arg, strict
478
+ )
479
+
480
+ async def eval_on_selector_all(
481
+ self, selector: str, expression: str, arg: Serializable = None
482
+ ) -> Any:
483
+ return await self._main_frame.eval_on_selector_all(selector, expression, arg)
484
+
485
+ async def add_script_tag(
486
+ self,
487
+ url: str = None,
488
+ path: Union[str, Path] = None,
489
+ content: str = None,
490
+ type: str = None,
491
+ ) -> ElementHandle:
492
+ return await self._main_frame.add_script_tag(**locals_to_params(locals()))
493
+
494
+ async def add_style_tag(
495
+ self, url: str = None, path: Union[str, Path] = None, content: str = None
496
+ ) -> ElementHandle:
497
+ return await self._main_frame.add_style_tag(**locals_to_params(locals()))
498
+
499
+ async def expose_function(self, name: str, callback: Callable) -> Disposable:
500
+ return await self.expose_binding(name, lambda source, *args: callback(*args))
501
+
502
+ async def expose_binding(self, name: str, callback: Callable) -> Disposable:
503
+ await self.install_inject_route()
504
+ if name in self._bindings:
505
+ raise Error(f'Function "{name}" has been already registered')
506
+ if name in self._browser_context._bindings:
507
+ raise Error(
508
+ f'Function "{name}" has been already registered in the browser context'
509
+ )
510
+ self._bindings[name] = callback
511
+ return from_channel(
512
+ await self._channel.send("exposeBinding", None, dict(name=name))
513
+ )
514
+
515
+ async def set_extra_http_headers(self, headers: Dict[str, str]) -> None:
516
+ await self._channel.send(
517
+ "setExtraHTTPHeaders", None, dict(headers=serialize_headers(headers))
518
+ )
519
+
520
+ @property
521
+ def url(self) -> str:
522
+ return self._main_frame.url
523
+
524
+ async def content(self) -> str:
525
+ return await self._main_frame.content()
526
+
527
+ async def set_content(
528
+ self, html: str, timeout: float = None, waitUntil: DocumentLoadState = None
529
+ ) -> None:
530
+ return await self._main_frame.set_content(**locals_to_params(locals()))
531
+
532
+ async def goto(
533
+ self,
534
+ url: str,
535
+ timeout: float = None,
536
+ waitUntil: DocumentLoadState = None,
537
+ referer: str = None,
538
+ ) -> Optional[Response]:
539
+ return await self._main_frame.goto(**locals_to_params(locals()))
540
+
541
+ async def reload(
542
+ self, timeout: float = None, waitUntil: DocumentLoadState = None
543
+ ) -> Optional[Response]:
544
+ return from_nullable_channel(
545
+ await self._channel.send(
546
+ "reload",
547
+ self._timeout_settings.navigation_timeout,
548
+ locals_to_params(locals()),
549
+ )
550
+ )
551
+
552
+ async def wait_for_load_state(
553
+ self,
554
+ state: Literal["domcontentloaded", "load", "networkidle"] = None,
555
+ timeout: float = None,
556
+ ) -> None:
557
+ return await self._main_frame.wait_for_load_state(**locals_to_params(locals()))
558
+
559
+ async def wait_for_url(
560
+ self, url: URLMatch, waitUntil: DocumentLoadState = None, timeout: float = None
561
+ ) -> None:
562
+ return await self._main_frame.wait_for_url(**locals_to_params(locals()))
563
+
564
+ async def wait_for_event(
565
+ self, event: str, predicate: Callable = None, timeout: float = None
566
+ ) -> Any:
567
+ async with self.expect_event(event, predicate, timeout) as event_info:
568
+ pass
569
+ return await event_info
570
+
571
+ async def go_back(
572
+ self, timeout: float = None, waitUntil: DocumentLoadState = None
573
+ ) -> Optional[Response]:
574
+ return from_nullable_channel(
575
+ await self._channel.send(
576
+ "goBack",
577
+ self._timeout_settings.navigation_timeout,
578
+ locals_to_params(locals()),
579
+ )
580
+ )
581
+
582
+ async def go_forward(
583
+ self, timeout: float = None, waitUntil: DocumentLoadState = None
584
+ ) -> Optional[Response]:
585
+ return from_nullable_channel(
586
+ await self._channel.send(
587
+ "goForward",
588
+ self._timeout_settings.navigation_timeout,
589
+ locals_to_params(locals()),
590
+ )
591
+ )
592
+
593
+ async def request_gc(self) -> None:
594
+ await self._channel.send("requestGC", None)
595
+
596
+ async def emulate_media(
597
+ self,
598
+ media: Literal["null", "print", "screen"] = None,
599
+ colorScheme: ColorScheme = None,
600
+ reducedMotion: ReducedMotion = None,
601
+ forcedColors: ForcedColors = None,
602
+ contrast: Contrast = None,
603
+ ) -> None:
604
+ params = locals_to_params(locals())
605
+ if "media" in params:
606
+ params["media"] = "no-override" if params["media"] == "null" else media
607
+ if "colorScheme" in params:
608
+ params["colorScheme"] = (
609
+ "no-override" if params["colorScheme"] == "null" else colorScheme
610
+ )
611
+ if "reducedMotion" in params:
612
+ params["reducedMotion"] = (
613
+ "no-override" if params["reducedMotion"] == "null" else reducedMotion
614
+ )
615
+ if "forcedColors" in params:
616
+ params["forcedColors"] = (
617
+ "no-override" if params["forcedColors"] == "null" else forcedColors
618
+ )
619
+ if "contrast" in params:
620
+ params["contrast"] = (
621
+ "no-override" if params["contrast"] == "null" else contrast
622
+ )
623
+ await self._channel.send("emulateMedia", None, params)
624
+
625
+ async def set_viewport_size(self, viewportSize: ViewportSize) -> None:
626
+ self._viewport_size = viewportSize
627
+ await self._channel.send("setViewportSize", None, locals_to_params(locals()))
628
+
629
+ @property
630
+ def viewport_size(self) -> Optional[ViewportSize]:
631
+ return self._viewport_size
632
+
633
+ async def bring_to_front(self) -> None:
634
+ await self._channel.send("bringToFront", None)
635
+
636
+ async def hide_highlight(self) -> None:
637
+ await self._channel.send("hideHighlight", None)
638
+
639
+ async def add_init_script(
640
+ self, script: str = None, path: Union[str, Path] = None
641
+ ) -> Disposable:
642
+ await self.install_inject_route()
643
+ if path:
644
+ script = add_source_url_to_script(
645
+ (await async_readfile(path)).decode(), path
646
+ )
647
+ if not isinstance(script, str):
648
+ raise Error("Either path or script parameter must be specified")
649
+ return from_channel(
650
+ await self._channel.send("addInitScript", None, dict(source=script))
651
+ )
652
+
653
+ async def route(
654
+ self, url: URLMatch, handler: RouteHandlerCallback, times: int = None
655
+ ) -> DisposableStub:
656
+ self._routes.insert(
657
+ 0,
658
+ RouteHandler(
659
+ self._browser_context._base_url,
660
+ url,
661
+ handler,
662
+ True if self._dispatcher_fiber else False,
663
+ times,
664
+ ),
665
+ )
666
+ await self._update_interception_patterns()
667
+ return DisposableStub(lambda: self.unroute(url, handler), self)
668
+
669
+ async def unroute(
670
+ self, url: URLMatch, handler: Optional[RouteHandlerCallback] = None
671
+ ) -> None:
672
+ removed = []
673
+ remaining = []
674
+ for route in self._routes:
675
+ if route.url != url or (handler and route.handler != handler):
676
+ remaining.append(route)
677
+ else:
678
+ removed.append(route)
679
+ await self._unroute_internal(removed, remaining, "default")
680
+
681
+ async def _unroute_internal(
682
+ self,
683
+ removed: List[RouteHandler],
684
+ remaining: List[RouteHandler],
685
+ behavior: Literal["default", "ignoreErrors", "wait"] = None,
686
+ ) -> None:
687
+ self._routes = remaining
688
+ if behavior is not None and behavior != "default":
689
+ await asyncio.gather(*map(lambda route: route.stop(behavior), removed))
690
+ await self._update_interception_patterns()
691
+
692
+ async def route_web_socket(
693
+ self, url: URLMatch, handler: WebSocketRouteHandlerCallback
694
+ ) -> None:
695
+ self._web_socket_routes.insert(
696
+ 0, WebSocketRouteHandler(self._browser_context._base_url, url, handler)
697
+ )
698
+ await self._update_web_socket_interception_patterns()
699
+
700
+ def _dispose_har_routers(self) -> None:
701
+ for router in self._har_routers:
702
+ router.dispose()
703
+ self._har_routers = []
704
+
705
+ async def unroute_all(
706
+ self, behavior: Literal["default", "ignoreErrors", "wait"] = None
707
+ ) -> None:
708
+ await self._unroute_internal(self._routes, [], behavior)
709
+ self._dispose_har_routers()
710
+
711
+ async def route_from_har(
712
+ self,
713
+ har: Union[Path, str],
714
+ url: Union[Pattern[str], str] = None,
715
+ notFound: RouteFromHarNotFoundPolicy = None,
716
+ update: bool = None,
717
+ updateContent: Literal["attach", "embed"] = None,
718
+ updateMode: HarMode = None,
719
+ ) -> None:
720
+ if update:
721
+ await self._browser_context._tracing._record_into_har(
722
+ har=har,
723
+ page=self,
724
+ url=url,
725
+ update_content=updateContent,
726
+ update_mode=updateMode,
727
+ )
728
+ return
729
+ router = await HarRouter.create(
730
+ local_utils=self._connection.local_utils,
731
+ file=str(har),
732
+ not_found_action=notFound or "abort",
733
+ url_matcher=url,
734
+ )
735
+ self._har_routers.append(router)
736
+ await router.add_page_route(self)
737
+
738
+ async def _update_interception_patterns(self) -> None:
739
+ patterns = RouteHandler.prepare_interception_patterns(self._routes)
740
+ await self._channel.send(
741
+ "setNetworkInterceptionPatterns", None, {"patterns": patterns}
742
+ )
743
+
744
+ async def _update_web_socket_interception_patterns(self) -> None:
745
+ patterns = WebSocketRouteHandler.prepare_interception_patterns(
746
+ self._web_socket_routes
747
+ )
748
+ await self._channel.send(
749
+ "setWebSocketInterceptionPatterns", None, {"patterns": patterns}
750
+ )
751
+
752
+ async def screenshot(
753
+ self,
754
+ timeout: float = None,
755
+ type: Literal["jpeg", "png", "webp"] = None,
756
+ path: Union[str, Path] = None,
757
+ quality: int = None,
758
+ omitBackground: bool = None,
759
+ fullPage: bool = None,
760
+ clip: FloatRect = None,
761
+ animations: Literal["allow", "disabled"] = None,
762
+ caret: Literal["hide", "initial"] = None,
763
+ scale: Literal["css", "device"] = None,
764
+ mask: Sequence["Locator"] = None,
765
+ maskColor: str = None,
766
+ style: str = None,
767
+ ) -> bytes:
768
+ params = locals_to_params(locals())
769
+ if "path" in params:
770
+ if "type" not in params:
771
+ params["type"] = determine_screenshot_type(params["path"])
772
+ del params["path"]
773
+ if "mask" in params:
774
+ params["mask"] = list(
775
+ map(
776
+ lambda locator: {
777
+ "frame": locator._frame._channel,
778
+ "selector": locator._selector,
779
+ },
780
+ params["mask"],
781
+ )
782
+ )
783
+ encoded_binary = await self._channel.send(
784
+ "screenshot", self._timeout_settings.timeout, params
785
+ )
786
+ decoded_binary = base64.b64decode(encoded_binary)
787
+ if path:
788
+ make_dirs_for_file(path)
789
+ await async_writefile(path, decoded_binary)
790
+ return decoded_binary
791
+
792
+ async def title(self) -> str:
793
+ return await self._main_frame.title()
794
+
795
+ async def aria_snapshot(
796
+ self,
797
+ timeout: float = None,
798
+ depth: int = None,
799
+ mode: Literal["ai", "default"] = None,
800
+ boxes: bool = None,
801
+ ) -> str:
802
+ return await self._main_frame._channel.send(
803
+ "ariaSnapshot", self._main_frame._timeout, locals_to_params(locals())
804
+ )
805
+
806
+ async def close(self, runBeforeUnload: bool = None, reason: str = None) -> None:
807
+ self._close_reason = reason
808
+ if not runBeforeUnload:
809
+ self._close_was_called = True
810
+ try:
811
+ if self._owned_context:
812
+ await self._owned_context.close()
813
+ elif runBeforeUnload:
814
+ await self._channel.send("runBeforeUnload", None)
815
+ else:
816
+ await self._channel.send("close", None, {"reason": reason})
817
+ except Exception as e:
818
+ if is_target_closed_error(e) and (not runBeforeUnload):
819
+ return
820
+ raise e
821
+
822
+ def is_closed(self) -> bool:
823
+ return self._is_closed
824
+
825
+ async def click(
826
+ self,
827
+ selector: str,
828
+ modifiers: Sequence[KeyboardModifier] = None,
829
+ position: Position = None,
830
+ delay: float = None,
831
+ button: MouseButton = None,
832
+ clickCount: int = None,
833
+ timeout: float = None,
834
+ force: bool = None,
835
+ noWaitAfter: bool = None,
836
+ trial: bool = None,
837
+ strict: bool = None,
838
+ scroll: Literal["auto", "none"] = None,
839
+ ) -> None:
840
+ return await self._main_frame._click(**locals_to_params(locals()))
841
+
842
+ async def dblclick(
843
+ self,
844
+ selector: str,
845
+ modifiers: Sequence[KeyboardModifier] = None,
846
+ position: Position = None,
847
+ delay: float = None,
848
+ button: MouseButton = None,
849
+ timeout: float = None,
850
+ force: bool = None,
851
+ noWaitAfter: bool = None,
852
+ strict: bool = None,
853
+ trial: bool = None,
854
+ scroll: Literal["auto", "none"] = None,
855
+ ) -> None:
856
+ return await self._main_frame.dblclick(**locals_to_params(locals()))
857
+
858
+ async def tap(
859
+ self,
860
+ selector: str,
861
+ modifiers: Sequence[KeyboardModifier] = None,
862
+ position: Position = None,
863
+ timeout: float = None,
864
+ force: bool = None,
865
+ noWaitAfter: bool = None,
866
+ strict: bool = None,
867
+ trial: bool = None,
868
+ scroll: Literal["auto", "none"] = None,
869
+ ) -> None:
870
+ return await self._main_frame.tap(**locals_to_params(locals()))
871
+
872
+ async def fill(
873
+ self,
874
+ selector: str,
875
+ value: str,
876
+ timeout: float = None,
877
+ noWaitAfter: bool = None,
878
+ strict: bool = None,
879
+ force: bool = None,
880
+ ) -> None:
881
+ return await self._main_frame.fill(**locals_to_params(locals()))
882
+
883
+ def locator(
884
+ self,
885
+ selector: str,
886
+ hasText: Union[str, Pattern[str]] = None,
887
+ hasNotText: Union[str, Pattern[str]] = None,
888
+ has: "Locator" = None,
889
+ hasNot: "Locator" = None,
890
+ ) -> "Locator":
891
+ return self._main_frame.locator(
892
+ selector, hasText=hasText, hasNotText=hasNotText, has=has, hasNot=hasNot
893
+ )
894
+
895
+ def get_by_alt_text(
896
+ self, text: Union[str, Pattern[str]], exact: bool = None
897
+ ) -> "Locator":
898
+ return self._main_frame.get_by_alt_text(text, exact=exact)
899
+
900
+ def get_by_label(
901
+ self, text: Union[str, Pattern[str]], exact: bool = None
902
+ ) -> "Locator":
903
+ return self._main_frame.get_by_label(text, exact=exact)
904
+
905
+ def get_by_placeholder(
906
+ self, text: Union[str, Pattern[str]], exact: bool = None
907
+ ) -> "Locator":
908
+ return self._main_frame.get_by_placeholder(text, exact=exact)
909
+
910
+ def get_by_role(
911
+ self,
912
+ role: AriaRole,
913
+ checked: bool = None,
914
+ disabled: bool = None,
915
+ expanded: bool = None,
916
+ includeHidden: bool = None,
917
+ level: int = None,
918
+ name: Union[str, Pattern[str]] = None,
919
+ pressed: bool = None,
920
+ selected: bool = None,
921
+ exact: bool = None,
922
+ description: Union[str, Pattern[str]] = None,
923
+ ) -> "Locator":
924
+ return self._main_frame.get_by_role(
925
+ role,
926
+ checked=checked,
927
+ disabled=disabled,
928
+ expanded=expanded,
929
+ includeHidden=includeHidden,
930
+ level=level,
931
+ name=name,
932
+ pressed=pressed,
933
+ selected=selected,
934
+ exact=exact,
935
+ description=description,
936
+ )
937
+
938
+ def get_by_test_id(self, testId: Union[str, Pattern[str]]) -> "Locator":
939
+ return self._main_frame.get_by_test_id(testId)
940
+
941
+ def get_by_text(
942
+ self, text: Union[str, Pattern[str]], exact: bool = None
943
+ ) -> "Locator":
944
+ return self._main_frame.get_by_text(text, exact=exact)
945
+
946
+ def get_by_title(
947
+ self, text: Union[str, Pattern[str]], exact: bool = None
948
+ ) -> "Locator":
949
+ return self._main_frame.get_by_title(text, exact=exact)
950
+
951
+ def frame_locator(self, selector: str) -> "FrameLocator":
952
+ return self.main_frame.frame_locator(selector)
953
+
954
+ async def focus(
955
+ self, selector: str, strict: bool = None, timeout: float = None
956
+ ) -> None:
957
+ return await self._main_frame.focus(**locals_to_params(locals()))
958
+
959
+ async def text_content(
960
+ self, selector: str, strict: bool = None, timeout: float = None
961
+ ) -> Optional[str]:
962
+ return await self._main_frame.text_content(**locals_to_params(locals()))
963
+
964
+ async def inner_text(
965
+ self, selector: str, strict: bool = None, timeout: float = None
966
+ ) -> str:
967
+ return await self._main_frame.inner_text(**locals_to_params(locals()))
968
+
969
+ async def inner_html(
970
+ self, selector: str, strict: bool = None, timeout: float = None
971
+ ) -> str:
972
+ return await self._main_frame.inner_html(**locals_to_params(locals()))
973
+
974
+ async def get_attribute(
975
+ self, selector: str, name: str, strict: bool = None, timeout: float = None
976
+ ) -> Optional[str]:
977
+ return await self._main_frame.get_attribute(**locals_to_params(locals()))
978
+
979
+ async def hover(
980
+ self,
981
+ selector: str,
982
+ modifiers: Sequence[KeyboardModifier] = None,
983
+ position: Position = None,
984
+ timeout: float = None,
985
+ noWaitAfter: bool = None,
986
+ force: bool = None,
987
+ strict: bool = None,
988
+ trial: bool = None,
989
+ scroll: Literal["auto", "none"] = None,
990
+ ) -> None:
991
+ return await self._main_frame.hover(**locals_to_params(locals()))
992
+
993
+ async def drag_and_drop(
994
+ self,
995
+ source: str,
996
+ target: str,
997
+ sourcePosition: Position = None,
998
+ targetPosition: Position = None,
999
+ force: bool = None,
1000
+ noWaitAfter: bool = None,
1001
+ timeout: float = None,
1002
+ strict: bool = None,
1003
+ trial: bool = None,
1004
+ steps: int = None,
1005
+ scroll: Literal["auto", "none"] = None,
1006
+ ) -> None:
1007
+ return await self._main_frame.drag_and_drop(**locals_to_params(locals()))
1008
+
1009
+ async def select_option(
1010
+ self,
1011
+ selector: str,
1012
+ value: Union[str, Sequence[str]] = None,
1013
+ index: Union[int, Sequence[int]] = None,
1014
+ label: Union[str, Sequence[str]] = None,
1015
+ element: Union["ElementHandle", Sequence["ElementHandle"]] = None,
1016
+ timeout: float = None,
1017
+ noWaitAfter: bool = None,
1018
+ force: bool = None,
1019
+ strict: bool = None,
1020
+ ) -> List[str]:
1021
+ params = locals_to_params(locals())
1022
+ return await self._main_frame.select_option(**params)
1023
+
1024
+ async def input_value(
1025
+ self, selector: str, strict: bool = None, timeout: float = None
1026
+ ) -> str:
1027
+ params = locals_to_params(locals())
1028
+ return await self._main_frame.input_value(**params)
1029
+
1030
+ async def set_input_files(
1031
+ self,
1032
+ selector: str,
1033
+ files: Union[
1034
+ str, Path, FilePayload, Sequence[Union[str, Path]], Sequence[FilePayload]
1035
+ ],
1036
+ timeout: float = None,
1037
+ strict: bool = None,
1038
+ noWaitAfter: bool = None,
1039
+ ) -> None:
1040
+ return await self._main_frame.set_input_files(**locals_to_params(locals()))
1041
+
1042
+ async def type(
1043
+ self,
1044
+ selector: str,
1045
+ text: str,
1046
+ delay: float = None,
1047
+ timeout: float = None,
1048
+ noWaitAfter: bool = None,
1049
+ strict: bool = None,
1050
+ ) -> None:
1051
+ return await self._main_frame.type(**locals_to_params(locals()))
1052
+
1053
+ async def press(
1054
+ self,
1055
+ selector: str,
1056
+ key: str,
1057
+ delay: float = None,
1058
+ timeout: float = None,
1059
+ noWaitAfter: bool = None,
1060
+ strict: bool = None,
1061
+ ) -> None:
1062
+ return await self._main_frame.press(**locals_to_params(locals()))
1063
+
1064
+ async def check(
1065
+ self,
1066
+ selector: str,
1067
+ position: Position = None,
1068
+ timeout: float = None,
1069
+ force: bool = None,
1070
+ noWaitAfter: bool = None,
1071
+ strict: bool = None,
1072
+ trial: bool = None,
1073
+ scroll: Literal["auto", "none"] = None,
1074
+ ) -> None:
1075
+ return await self._main_frame.check(**locals_to_params(locals()))
1076
+
1077
+ async def uncheck(
1078
+ self,
1079
+ selector: str,
1080
+ position: Position = None,
1081
+ timeout: float = None,
1082
+ force: bool = None,
1083
+ noWaitAfter: bool = None,
1084
+ strict: bool = None,
1085
+ trial: bool = None,
1086
+ scroll: Literal["auto", "none"] = None,
1087
+ ) -> None:
1088
+ return await self._main_frame.uncheck(**locals_to_params(locals()))
1089
+
1090
+ async def wait_for_timeout(self, timeout: float) -> None:
1091
+ await self._main_frame.wait_for_timeout(timeout)
1092
+
1093
+ async def wait_for_function(
1094
+ self,
1095
+ expression: str,
1096
+ arg: Serializable = None,
1097
+ timeout: float = None,
1098
+ polling: Union[float, Literal["raf"]] = None,
1099
+ ) -> JSHandle:
1100
+ return await self._main_frame.wait_for_function(**locals_to_params(locals()))
1101
+
1102
+ @property
1103
+ def workers(self) -> List["Worker"]:
1104
+ return self._workers.copy()
1105
+
1106
+ @property
1107
+ def request(self) -> "APIRequestContext":
1108
+ return self.context.request
1109
+
1110
+ async def pause(self) -> None:
1111
+ default_navigation_timeout = (
1112
+ self._browser_context._timeout_settings.default_navigation_timeout()
1113
+ )
1114
+ default_timeout = self._browser_context._timeout_settings.default_timeout()
1115
+ self._browser_context.set_default_navigation_timeout(0)
1116
+ self._browser_context.set_default_timeout(0)
1117
+ try:
1118
+ await asyncio.wait(
1119
+ [
1120
+ asyncio.create_task(
1121
+ self._browser_context._channel.send("pause", None)
1122
+ ),
1123
+ self._closed_or_crashed_future,
1124
+ ],
1125
+ return_when=asyncio.FIRST_COMPLETED,
1126
+ )
1127
+ finally:
1128
+ self._browser_context._set_default_navigation_timeout_impl(
1129
+ default_navigation_timeout
1130
+ )
1131
+ self._browser_context._set_default_timeout_impl(default_timeout)
1132
+
1133
+ async def pdf(
1134
+ self,
1135
+ scale: float = None,
1136
+ displayHeaderFooter: bool = None,
1137
+ headerTemplate: str = None,
1138
+ footerTemplate: str = None,
1139
+ printBackground: bool = None,
1140
+ landscape: bool = None,
1141
+ pageRanges: str = None,
1142
+ format: str = None,
1143
+ width: Union[str, float] = None,
1144
+ height: Union[str, float] = None,
1145
+ preferCSSPageSize: bool = None,
1146
+ margin: PdfMargins = None,
1147
+ path: Union[str, Path] = None,
1148
+ outline: bool = None,
1149
+ tagged: bool = None,
1150
+ ) -> bytes:
1151
+ params = locals_to_params(locals())
1152
+ if "path" in params:
1153
+ del params["path"]
1154
+ encoded_binary = await self._channel.send("pdf", None, params)
1155
+ decoded_binary = base64.b64decode(encoded_binary)
1156
+ if path:
1157
+ make_dirs_for_file(path)
1158
+ await async_writefile(path, decoded_binary)
1159
+ return decoded_binary
1160
+
1161
+ @property
1162
+ def video(self) -> Optional[Video]:
1163
+ if self._browser_context._options.get("recordVideo") is None:
1164
+ return None
1165
+ return self._video
1166
+
1167
+ @property
1168
+ def screencast(self) -> Screencast:
1169
+ return self._screencast
1170
+
1171
+ @property
1172
+ def local_storage(self) -> WebStorage:
1173
+ return self._local_storage
1174
+
1175
+ @property
1176
+ def session_storage(self) -> WebStorage:
1177
+ return self._session_storage
1178
+
1179
+ def _close_error_with_reason(self) -> TargetClosedError:
1180
+ return TargetClosedError(
1181
+ self._close_reason or self._browser_context._effective_close_reason()
1182
+ )
1183
+
1184
+ def expect_event(
1185
+ self, event: str, predicate: Callable = None, timeout: float = None
1186
+ ) -> EventContextManagerImpl:
1187
+ return self._expect_event(
1188
+ event, predicate, timeout, f'waiting for event "{event}"'
1189
+ )
1190
+
1191
+ def _expect_event(
1192
+ self,
1193
+ event: str,
1194
+ predicate: Callable = None,
1195
+ timeout: float = None,
1196
+ log_line: str = None,
1197
+ ) -> EventContextManagerImpl:
1198
+ if timeout is None:
1199
+ timeout = self._timeout_settings.timeout()
1200
+ waiter = Waiter(self, f"page.expect_event({event})")
1201
+ waiter.reject_on_timeout(
1202
+ timeout, f'Timeout {timeout}ms exceeded while waiting for event "{event}"'
1203
+ )
1204
+ if log_line:
1205
+ waiter.log(log_line)
1206
+ if event != Page.Events.Crash:
1207
+ waiter.reject_on_event(self, Page.Events.Crash, Error("Page crashed"))
1208
+ if event != Page.Events.Close:
1209
+ waiter.reject_on_event(
1210
+ self, Page.Events.Close, lambda: self._close_error_with_reason()
1211
+ )
1212
+ waiter.wait_for_event(self, event, predicate)
1213
+ return EventContextManagerImpl(waiter.result())
1214
+
1215
+ def expect_console_message(
1216
+ self, predicate: Callable[[ConsoleMessage], bool] = None, timeout: float = None
1217
+ ) -> EventContextManagerImpl[ConsoleMessage]:
1218
+ return self.expect_event(Page.Events.Console, predicate, timeout)
1219
+
1220
+ def expect_download(
1221
+ self, predicate: Callable[[Download], bool] = None, timeout: float = None
1222
+ ) -> EventContextManagerImpl[Download]:
1223
+ return self.expect_event(Page.Events.Download, predicate, timeout)
1224
+
1225
+ def expect_file_chooser(
1226
+ self, predicate: Callable[[FileChooser], bool] = None, timeout: float = None
1227
+ ) -> EventContextManagerImpl[FileChooser]:
1228
+ return self.expect_event(Page.Events.FileChooser, predicate, timeout)
1229
+
1230
+ def expect_navigation(
1231
+ self,
1232
+ url: URLMatch = None,
1233
+ waitUntil: DocumentLoadState = None,
1234
+ timeout: float = None,
1235
+ ) -> EventContextManagerImpl[Response]:
1236
+ return self.main_frame.expect_navigation(url, waitUntil, timeout)
1237
+
1238
+ def expect_popup(
1239
+ self, predicate: Callable[["Page"], bool] = None, timeout: float = None
1240
+ ) -> EventContextManagerImpl["Page"]:
1241
+ return self.expect_event(Page.Events.Popup, predicate, timeout)
1242
+
1243
+ def expect_request(
1244
+ self, urlOrPredicate: URLMatchRequest, timeout: float = None
1245
+ ) -> EventContextManagerImpl[Request]:
1246
+
1247
+ def my_predicate(request: Request) -> Union[bool, Awaitable[bool]]:
1248
+ if not callable(urlOrPredicate):
1249
+ return url_matches(
1250
+ self._browser_context._base_url, request.url, urlOrPredicate
1251
+ )
1252
+ return urlOrPredicate(request)
1253
+
1254
+ trimmed_url = trim_url(urlOrPredicate)
1255
+ log_line = f"waiting for request {trimmed_url}" if trimmed_url else None
1256
+ return self._expect_event(
1257
+ Page.Events.Request,
1258
+ predicate=my_predicate,
1259
+ timeout=timeout,
1260
+ log_line=log_line,
1261
+ )
1262
+
1263
+ def expect_request_finished(
1264
+ self, predicate: Callable[["Request"], bool] = None, timeout: float = None
1265
+ ) -> EventContextManagerImpl[Request]:
1266
+ return self.expect_event(
1267
+ Page.Events.RequestFinished, predicate=predicate, timeout=timeout
1268
+ )
1269
+
1270
+ def expect_response(
1271
+ self, urlOrPredicate: URLMatchResponse, timeout: float = None
1272
+ ) -> EventContextManagerImpl[Response]:
1273
+
1274
+ def my_predicate(request: Response) -> Union[bool, Awaitable[bool]]:
1275
+ if not callable(urlOrPredicate):
1276
+ return url_matches(
1277
+ self._browser_context._base_url, request.url, urlOrPredicate
1278
+ )
1279
+ return urlOrPredicate(request)
1280
+
1281
+ trimmed_url = trim_url(urlOrPredicate)
1282
+ log_line = f"waiting for response {trimmed_url}" if trimmed_url else None
1283
+ return self._expect_event(
1284
+ Page.Events.Response,
1285
+ predicate=my_predicate,
1286
+ timeout=timeout,
1287
+ log_line=log_line,
1288
+ )
1289
+
1290
+ def expect_websocket(
1291
+ self, predicate: Callable[["WebSocket"], bool] = None, timeout: float = None
1292
+ ) -> EventContextManagerImpl["WebSocket"]:
1293
+ return self.expect_event("websocket", predicate, timeout)
1294
+
1295
+ def expect_worker(
1296
+ self, predicate: Callable[["Worker"], bool] = None, timeout: float = None
1297
+ ) -> EventContextManagerImpl["Worker"]:
1298
+ return self.expect_event("worker", predicate, timeout)
1299
+
1300
+ async def set_checked(
1301
+ self,
1302
+ selector: str,
1303
+ checked: bool,
1304
+ position: Position = None,
1305
+ timeout: float = None,
1306
+ force: bool = None,
1307
+ noWaitAfter: bool = None,
1308
+ strict: bool = None,
1309
+ trial: bool = None,
1310
+ scroll: Literal["auto", "none"] = None,
1311
+ ) -> None:
1312
+ if checked:
1313
+ await self.check(
1314
+ selector=selector,
1315
+ position=position,
1316
+ timeout=timeout,
1317
+ force=force,
1318
+ strict=strict,
1319
+ trial=trial,
1320
+ scroll=scroll,
1321
+ )
1322
+ else:
1323
+ await self.uncheck(
1324
+ selector=selector,
1325
+ position=position,
1326
+ timeout=timeout,
1327
+ force=force,
1328
+ strict=strict,
1329
+ trial=trial,
1330
+ scroll=scroll,
1331
+ )
1332
+
1333
+ async def add_locator_handler(
1334
+ self,
1335
+ locator: "Locator",
1336
+ handler: Union[Callable[["Locator"], Any], Callable[[], Any]],
1337
+ noWaitAfter: bool = None,
1338
+ times: int = None,
1339
+ ) -> None:
1340
+ if locator._frame != self._main_frame:
1341
+ raise Error("Locator must belong to the main frame of this page")
1342
+ if times == 0:
1343
+ return
1344
+ uid = await self._channel.send(
1345
+ "registerLocatorHandler",
1346
+ None,
1347
+ {"selector": locator._selector, "noWaitAfter": noWaitAfter},
1348
+ )
1349
+ self._locator_handlers[uid] = LocatorHandler(
1350
+ handler=handler, times=times, locator=locator
1351
+ )
1352
+
1353
+ async def _on_locator_handler_triggered(self, uid: str) -> None:
1354
+ remove = False
1355
+ try:
1356
+ handler = self._locator_handlers.get(uid)
1357
+ if handler and handler.times != 0:
1358
+ if handler.times is not None:
1359
+ handler.times -= 1
1360
+ if self._dispatcher_fiber:
1361
+ handler_finished_future = self._loop.create_future()
1362
+
1363
+ def _handler() -> None:
1364
+ try:
1365
+ handler()
1366
+ handler_finished_future.set_result(None)
1367
+ except Exception as e:
1368
+ handler_finished_future.set_exception(e)
1369
+
1370
+ g = LocatorHandlerGreenlet(_handler)
1371
+ g.switch()
1372
+ await handler_finished_future
1373
+ else:
1374
+ coro_or_future = handler()
1375
+ if coro_or_future:
1376
+ await coro_or_future
1377
+ remove = handler.times == 0
1378
+ finally:
1379
+ if remove:
1380
+ del self._locator_handlers[uid]
1381
+ try:
1382
+ await self._connection.wrap_api_call(
1383
+ lambda: self._channel.send(
1384
+ "resolveLocatorHandlerNoReply",
1385
+ None,
1386
+ {"uid": uid, "remove": remove},
1387
+ ),
1388
+ is_internal=True,
1389
+ )
1390
+ except Error:
1391
+ pass
1392
+
1393
+ async def remove_locator_handler(self, locator: "Locator") -> None:
1394
+ for uid, data in self._locator_handlers.copy().items():
1395
+ if data.locator._equals(locator):
1396
+ del self._locator_handlers[uid]
1397
+ self._channel.send_no_reply(
1398
+ "unregisterLocatorHandler", None, {"uid": uid}
1399
+ )
1400
+
1401
+ async def requests(self) -> List[Request]:
1402
+ request_objects = await self._channel.send("requests", None)
1403
+ return [from_channel(r) for r in request_objects]
1404
+
1405
+ async def console_messages(
1406
+ self, filter: Literal["all", "since-navigation"] = None
1407
+ ) -> List[ConsoleMessage]:
1408
+ message_dicts = await self._channel.send(
1409
+ "consoleMessages", None, locals_to_params(locals())
1410
+ )
1411
+ return [
1412
+ ConsoleMessage(
1413
+ {**event, "page": self._channel}, self._loop, self._dispatcher_fiber
1414
+ )
1415
+ for event in message_dicts
1416
+ ]
1417
+
1418
+ async def page_errors(
1419
+ self, filter: Literal["all", "since-navigation"] = None
1420
+ ) -> List[Error]:
1421
+ error_objects = await self._channel.send(
1422
+ "pageErrors", None, locals_to_params(locals())
1423
+ )
1424
+ return [parse_error(error["error"]) for error in error_objects]
1425
+
1426
+ async def clear_console_messages(self) -> None:
1427
+ await self._channel.send("clearConsoleMessages", None)
1428
+
1429
+ async def clear_page_errors(self) -> None:
1430
+ await self._channel.send("clearPageErrors", None)
1431
+
1432
+ async def pick_locator(self) -> "Locator":
1433
+ selector = await self._channel.send("pickLocator", None, {})
1434
+ return self.locator(selector)
1435
+
1436
+ async def cancel_pick_locator(self) -> None:
1437
+ await self._channel.send("cancelPickLocator", None, {})
1438
+
1439
+ route_injecting = False
1440
+
1441
+ async def install_inject_route(self) -> None:
1442
+ from patchright._impl._impl_to_api_mapping import ImplToApiMapping
1443
+
1444
+ mapping = ImplToApiMapping()
1445
+
1446
+ async def route_handler(route: Route) -> None:
1447
+ try:
1448
+ if (
1449
+ route.request.resource_type == "document"
1450
+ and route.request.url.startswith("http")
1451
+ ):
1452
+ await route.fallback(patchrightInitScript=True)
1453
+ else:
1454
+ await route.fallback()
1455
+ except:
1456
+ await route.fallback()
1457
+
1458
+ if not self.route_injecting and (not self.context.route_injecting):
1459
+ if self._connection._is_sync:
1460
+ self._routes.insert(
1461
+ 0,
1462
+ RouteHandler(
1463
+ self._browser_context._options.get("baseURL"),
1464
+ "**/*",
1465
+ mapping.wrap_handler(route_handler),
1466
+ False,
1467
+ None,
1468
+ ),
1469
+ )
1470
+ await self._update_interception_patterns()
1471
+ else:
1472
+ await self.route("**/*", mapping.wrap_handler(route_handler))
1473
+ self.route_injecting = True
1474
+
1475
+
1476
+ class Worker(ChannelOwner):
1477
+ Events = SimpleNamespace(Close="close", Console="console")
1478
+
1479
+ def __init__(
1480
+ self, parent: ChannelOwner, type: str, guid: str, initializer: Dict
1481
+ ) -> None:
1482
+ super().__init__(parent, type, guid, initializer)
1483
+ self._set_event_to_subscription_mapping({Worker.Events.Console: "console"})
1484
+ self._channel.on("close", lambda _: self._on_close())
1485
+ self._page: Optional[Page] = None
1486
+ self._context: Optional["BrowserContext"] = None
1487
+
1488
+ def __repr__(self) -> str:
1489
+ return f"<Worker url={self.url!r}>"
1490
+
1491
+ def _on_close(self) -> None:
1492
+ if self._page:
1493
+ self._page._workers.remove(self)
1494
+ if self._context:
1495
+ self._context._service_workers.remove(self)
1496
+ self.emit(Worker.Events.Close, self)
1497
+
1498
+ @property
1499
+ def url(self) -> str:
1500
+ return self._initializer["url"]
1501
+
1502
+ async def evaluate(
1503
+ self,
1504
+ expression: str,
1505
+ arg: Serializable = None,
1506
+ *,
1507
+ isolatedContext: Optional[bool] = True,
1508
+ ) -> Any:
1509
+ return parse_result(
1510
+ await self._channel.send(
1511
+ "evaluateExpression",
1512
+ None,
1513
+ dict(
1514
+ expression=expression,
1515
+ arg=serialize_argument(arg),
1516
+ isolatedContext=isolatedContext,
1517
+ ),
1518
+ )
1519
+ )
1520
+
1521
+ async def evaluate_handle(
1522
+ self,
1523
+ expression: str,
1524
+ arg: Serializable = None,
1525
+ *,
1526
+ isolatedContext: Optional[bool] = True,
1527
+ ) -> JSHandle:
1528
+ return from_channel(
1529
+ await self._channel.send(
1530
+ "evaluateExpressionHandle",
1531
+ None,
1532
+ dict(
1533
+ expression=expression,
1534
+ arg=serialize_argument(arg),
1535
+ isolatedContext=isolatedContext,
1536
+ ),
1537
+ )
1538
+ )
1539
+
1540
+ def expect_event(
1541
+ self, event: str, predicate: Callable = None, timeout: float = None
1542
+ ) -> EventContextManagerImpl:
1543
+ if timeout is None:
1544
+ if self._page:
1545
+ timeout = self._page._timeout_settings.timeout()
1546
+ elif self._context:
1547
+ timeout = self._context._timeout_settings.timeout()
1548
+ else:
1549
+ timeout = 30000
1550
+ waiter = Waiter(self, f"worker.expect_event({event})")
1551
+ waiter.reject_on_timeout(
1552
+ cast(float, timeout),
1553
+ f'Timeout {timeout}ms exceeded while waiting for event "{event}"',
1554
+ )
1555
+ if event != Worker.Events.Close:
1556
+ waiter.reject_on_event(
1557
+ self, Worker.Events.Close, lambda: TargetClosedError()
1558
+ )
1559
+ waiter.wait_for_event(self, event, predicate)
1560
+ return EventContextManagerImpl(waiter.result())
1561
+
1562
+
1563
+ class BindingCall(ChannelOwner):
1564
+ def __init__(
1565
+ self, parent: ChannelOwner, type: str, guid: str, initializer: Dict
1566
+ ) -> None:
1567
+ super().__init__(parent, type, guid, initializer)
1568
+
1569
+ async def call(self, func: Callable) -> None:
1570
+ try:
1571
+ frame = from_channel(self._initializer["frame"])
1572
+ source = dict(context=frame._page.context, page=frame._page, frame=frame)
1573
+ if self._initializer.get("handle"):
1574
+ result = func(source, from_channel(self._initializer["handle"]))
1575
+ else:
1576
+ func_args = list(map(parse_result, self._initializer["args"]))
1577
+ result = func(source, *func_args)
1578
+ if inspect.iscoroutine(result):
1579
+ result = await result
1580
+ self._channel.send_may_fail(
1581
+ "resolve", None, dict(result=serialize_argument(result))
1582
+ )
1583
+ except Exception as e:
1584
+ tb = sys.exc_info()[2]
1585
+ self._channel.send_may_fail(
1586
+ "reject", None, dict(error=dict(error=serialize_error(e, tb)))
1587
+ )
1588
+
1589
+
1590
+ def trim_url(param: Union[URLMatchRequest, URLMatchResponse]) -> Optional[str]:
1591
+ if isinstance(param, re.Pattern):
1592
+ return trim_end(param.pattern)
1593
+ if isinstance(param, str):
1594
+ return trim_end(param)
1595
+ return None
1596
+
1597
+
1598
+ def trim_end(s: str) -> str:
1599
+ if len(s) > 50:
1600
+ return s[:50] + "…"
1601
+ return s