Best Python code snippet using playwright-python
_page.py
Source:_page.py
...229 finally:230 if not handler_entry.is_active:231 self._routes.remove(handler_entry)232 if len(self._routes) == 0:233 asyncio.create_task(self._disable_interception())234 return235 self._browser_context._on_route(route, request)236 def _on_binding(self, binding_call: "BindingCall") -> None:237 func = self._bindings.get(binding_call._initializer["name"])238 if func:239 asyncio.create_task(binding_call.call(func))240 self._browser_context._on_binding(binding_call)241 def _on_worker(self, worker: "Worker") -> None:242 self._workers.append(worker)243 worker._page = self244 self.emit(Page.Events.Worker, worker)245 def _on_close(self) -> None:246 self._is_closed = True247 if self in self._browser_context._pages:248 self._browser_context._pages.remove(self)249 if self in self._browser_context._background_pages:250 self._browser_context._background_pages.remove(self)251 self.emit(Page.Events.Close, self)252 def _on_crash(self) -> None:253 self.emit(Page.Events.Crash, self)254 def _on_dialog(self, params: Any) -> None:255 dialog = cast(Dialog, from_channel(params["dialog"]))256 if self.listeners(Page.Events.Dialog):257 self.emit(Page.Events.Dialog, dialog)258 else:259 if dialog.type == "beforeunload":260 asyncio.create_task(dialog.accept())261 else:262 asyncio.create_task(dialog.dismiss())263 def _on_download(self, params: Any) -> None:264 url = params["url"]265 suggested_filename = params["suggestedFilename"]266 artifact = cast(Artifact, from_channel(params["artifact"]))267 self.emit(268 Page.Events.Download, Download(self, url, suggested_filename, artifact)269 )270 def _on_video(self, params: Any) -> None:271 artifact = from_channel(params["artifact"])272 cast(Video, self.video)._artifact_ready(artifact)273 def _add_event_handler(self, event: str, k: Any, v: Any) -> None:274 if event == Page.Events.FileChooser and len(self.listeners(event)) == 0:275 self._channel.send_no_reply(276 "setFileChooserInterceptedNoReply", {"intercepted": True}277 )278 super()._add_event_handler(event, k, v)279 def remove_listener(self, event: str, f: Any) -> None:280 super().remove_listener(event, f)281 if event == Page.Events.FileChooser and len(self.listeners(event)) == 0:282 self._channel.send_no_reply(283 "setFileChooserInterceptedNoReply", {"intercepted": False}284 )285 @property286 def context(self) -> "BrowserContext":287 return self._browser_context288 async def opener(self) -> Optional["Page"]:289 if self._opener and self._opener.is_closed():290 return None291 return self._opener292 @property293 def main_frame(self) -> Frame:294 return self._main_frame295 def frame(self, name: str = None, url: URLMatch = None) -> Optional[Frame]:296 matcher = (297 URLMatcher(self._browser_context._options.get("baseURL"), url)298 if url299 else None300 )301 for frame in self._frames:302 if name and frame.name == name:303 return frame304 if url and matcher and matcher.matches(frame.url):305 return frame306 return None307 @property308 def frames(self) -> List[Frame]:309 return self._frames.copy()310 def set_default_navigation_timeout(self, timeout: float) -> None:311 self._timeout_settings.set_navigation_timeout(timeout)312 self._channel.send_no_reply(313 "setDefaultNavigationTimeoutNoReply", dict(timeout=timeout)314 )315 def set_default_timeout(self, timeout: float) -> None:316 self._timeout_settings.set_timeout(timeout)317 self._channel.send_no_reply("setDefaultTimeoutNoReply", dict(timeout=timeout))318 async def query_selector(319 self,320 selector: str,321 strict: bool = None,322 ) -> Optional[ElementHandle]:323 return await self._main_frame.query_selector(selector, strict)324 async def query_selector_all(self, selector: str) -> List[ElementHandle]:325 return await self._main_frame.query_selector_all(selector)326 async def wait_for_selector(327 self,328 selector: str,329 timeout: float = None,330 state: Literal["attached", "detached", "hidden", "visible"] = None,331 strict: bool = None,332 ) -> Optional[ElementHandle]:333 return await self._main_frame.wait_for_selector(**locals_to_params(locals()))334 async def is_checked(335 self, selector: str, strict: bool = None, timeout: float = None336 ) -> bool:337 return await self._main_frame.is_checked(**locals_to_params(locals()))338 async def is_disabled(339 self, selector: str, strict: bool = None, timeout: float = None340 ) -> bool:341 return await self._main_frame.is_disabled(**locals_to_params(locals()))342 async def is_editable(343 self, selector: str, strict: bool = None, timeout: float = None344 ) -> bool:345 return await self._main_frame.is_editable(**locals_to_params(locals()))346 async def is_enabled(347 self, selector: str, strict: bool = None, timeout: float = None348 ) -> bool:349 return await self._main_frame.is_enabled(**locals_to_params(locals()))350 async def is_hidden(351 self, selector: str, strict: bool = None, timeout: float = None352 ) -> bool:353 return await self._main_frame.is_hidden(**locals_to_params(locals()))354 async def is_visible(355 self, selector: str, strict: bool = None, timeout: float = None356 ) -> bool:357 return await self._main_frame.is_visible(**locals_to_params(locals()))358 async def dispatch_event(359 self,360 selector: str,361 type: str,362 eventInit: Dict = None,363 timeout: float = None,364 strict: bool = None,365 ) -> None:366 return await self._main_frame.dispatch_event(**locals_to_params(locals()))367 async def evaluate(self, expression: str, arg: Serializable = None) -> Any:368 return await self._main_frame.evaluate(expression, arg)369 async def evaluate_handle(370 self, expression: str, arg: Serializable = None371 ) -> JSHandle:372 return await self._main_frame.evaluate_handle(expression, arg)373 async def eval_on_selector(374 self,375 selector: str,376 expression: str,377 arg: Serializable = None,378 strict: bool = None,379 ) -> Any:380 return await self._main_frame.eval_on_selector(381 selector, expression, arg, strict382 )383 async def eval_on_selector_all(384 self,385 selector: str,386 expression: str,387 arg: Serializable = None,388 ) -> Any:389 return await self._main_frame.eval_on_selector_all(selector, expression, arg)390 async def add_script_tag(391 self,392 url: str = None,393 path: Union[str, Path] = None,394 content: str = None,395 type: str = None,396 ) -> ElementHandle:397 return await self._main_frame.add_script_tag(**locals_to_params(locals()))398 async def add_style_tag(399 self, url: str = None, path: Union[str, Path] = None, content: str = None400 ) -> ElementHandle:401 return await self._main_frame.add_style_tag(**locals_to_params(locals()))402 async def expose_function(self, name: str, callback: Callable) -> None:403 await self.expose_binding(name, lambda source, *args: callback(*args))404 async def expose_binding(405 self, name: str, callback: Callable, handle: bool = None406 ) -> None:407 if name in self._bindings:408 raise Error(f'Function "{name}" has been already registered')409 if name in self._browser_context._bindings:410 raise Error(411 f'Function "{name}" has been already registered in the browser context'412 )413 self._bindings[name] = callback414 await self._channel.send(415 "exposeBinding", dict(name=name, needsHandle=handle or False)416 )417 async def set_extra_http_headers(self, headers: Dict[str, str]) -> None:418 await self._channel.send(419 "setExtraHTTPHeaders", dict(headers=serialize_headers(headers))420 )421 @property422 def url(self) -> str:423 return self._main_frame.url424 async def content(self) -> str:425 return await self._main_frame.content()426 async def set_content(427 self,428 html: str,429 timeout: float = None,430 waitUntil: DocumentLoadState = None,431 ) -> None:432 return await self._main_frame.set_content(**locals_to_params(locals()))433 async def goto(434 self,435 url: str,436 timeout: float = None,437 waitUntil: DocumentLoadState = None,438 referer: str = None,439 ) -> Optional[Response]:440 return await self._main_frame.goto(**locals_to_params(locals()))441 async def reload(442 self,443 timeout: float = None,444 waitUntil: DocumentLoadState = None,445 ) -> Optional[Response]:446 return from_nullable_channel(447 await self._channel.send("reload", locals_to_params(locals()))448 )449 async def wait_for_load_state(450 self,451 state: Literal["domcontentloaded", "load", "networkidle"] = None,452 timeout: float = None,453 ) -> None:454 return await self._main_frame.wait_for_load_state(**locals_to_params(locals()))455 async def wait_for_url(456 self,457 url: URLMatch,458 wait_until: DocumentLoadState = None,459 timeout: float = None,460 ) -> None:461 return await self._main_frame.wait_for_url(**locals_to_params(locals()))462 async def wait_for_event(463 self, event: str, predicate: Callable = None, timeout: float = None464 ) -> Any:465 async with self.expect_event(event, predicate, timeout) as event_info:466 pass467 return await event_info468 async def go_back(469 self,470 timeout: float = None,471 waitUntil: DocumentLoadState = None,472 ) -> Optional[Response]:473 return from_nullable_channel(474 await self._channel.send("goBack", locals_to_params(locals()))475 )476 async def go_forward(477 self,478 timeout: float = None,479 waitUntil: DocumentLoadState = None,480 ) -> Optional[Response]:481 return from_nullable_channel(482 await self._channel.send("goForward", locals_to_params(locals()))483 )484 async def emulate_media(485 self,486 media: Literal["print", "screen"] = None,487 colorScheme: ColorScheme = None,488 reducedMotion: ReducedMotion = None,489 forcedColors: ForcedColors = None,490 ) -> None:491 await self._channel.send("emulateMedia", locals_to_params(locals()))492 async def set_viewport_size(self, viewportSize: ViewportSize) -> None:493 self._viewport_size = viewportSize494 await self._channel.send("setViewportSize", locals_to_params(locals()))495 @property496 def viewport_size(self) -> Optional[ViewportSize]:497 return self._viewport_size498 async def bring_to_front(self) -> None:499 await self._channel.send("bringToFront")500 async def add_init_script(501 self, script: str = None, path: Union[str, Path] = None502 ) -> None:503 if path:504 script = (await async_readfile(path)).decode()505 if not isinstance(script, str):506 raise Error("Either path or script parameter must be specified")507 await self._channel.send("addInitScript", dict(source=script))508 async def route(509 self, url: URLMatch, handler: RouteHandlerCallback, times: int = None510 ) -> None:511 self._routes.insert(512 0,513 RouteHandler(514 URLMatcher(self._browser_context._options.get("baseURL"), url),515 handler,516 times,517 ),518 )519 if len(self._routes) == 1:520 await self._channel.send(521 "setNetworkInterceptionEnabled", dict(enabled=True)522 )523 async def unroute(524 self, url: URLMatch, handler: Optional[RouteHandlerCallback] = None525 ) -> None:526 self._routes = list(527 filter(528 lambda r: r.matcher.match != url or (handler and r.handler != handler),529 self._routes,530 )531 )532 if len(self._routes) == 0:533 await self._disable_interception()534 async def _disable_interception(self) -> None:535 await self._channel.send("setNetworkInterceptionEnabled", dict(enabled=False))536 async def screenshot(537 self,538 timeout: float = None,539 type: Literal["jpeg", "png"] = None,540 path: Union[str, Path] = None,541 quality: int = None,542 omitBackground: bool = None,543 fullPage: bool = None,544 clip: FloatRect = None,545 animations: Literal["allow", "disabled"] = None,546 caret: Literal["hide", "initial"] = None,547 scale: Literal["css", "device"] = None,548 mask: List["Locator"] = None,...
_browser_context.py
Source:_browser_context.py
...152 finally:153 if not handler_entry.is_active:154 self._routes.remove(handler_entry)155 if not len(self._routes) == 0:156 asyncio.create_task(self._disable_interception())157 break158 route._internal_continue()159 def _on_binding(self, binding_call: BindingCall) -> None:160 func = self._bindings.get(binding_call._initializer["name"])161 if func is None:162 return163 asyncio.create_task(binding_call.call(func))164 def set_default_navigation_timeout(self, timeout: float) -> None:165 self._timeout_settings.set_navigation_timeout(timeout)166 self._channel.send_no_reply(167 "setDefaultNavigationTimeoutNoReply", dict(timeout=timeout)168 )169 def set_default_timeout(self, timeout: float) -> None:170 self._timeout_settings.set_timeout(timeout)171 self._channel.send_no_reply("setDefaultTimeoutNoReply", dict(timeout=timeout))172 @property173 def pages(self) -> List[Page]:174 return self._pages.copy()175 @property176 def browser(self) -> Optional["Browser"]:177 return self._browser178 async def new_page(self) -> Page:179 if self._owner_page:180 raise Error("Please use browser.new_context()")181 return from_channel(await self._channel.send("newPage"))182 async def cookies(self, urls: Union[str, List[str]] = None) -> List[Cookie]:183 if urls is None:184 urls = []185 if not isinstance(urls, list):186 urls = [urls]187 return await self._channel.send("cookies", dict(urls=urls))188 async def add_cookies(self, cookies: List[SetCookieParam]) -> None:189 await self._channel.send("addCookies", dict(cookies=cookies))190 async def clear_cookies(self) -> None:191 await self._channel.send("clearCookies")192 async def grant_permissions(193 self, permissions: List[str], origin: str = None194 ) -> None:195 await self._channel.send("grantPermissions", locals_to_params(locals()))196 async def clear_permissions(self) -> None:197 await self._channel.send("clearPermissions")198 async def set_geolocation(self, geolocation: Geolocation = None) -> None:199 await self._channel.send("setGeolocation", locals_to_params(locals()))200 async def set_extra_http_headers(self, headers: Dict[str, str]) -> None:201 await self._channel.send(202 "setExtraHTTPHeaders", dict(headers=serialize_headers(headers))203 )204 async def set_offline(self, offline: bool) -> None:205 await self._channel.send("setOffline", dict(offline=offline))206 async def add_init_script(207 self, script: str = None, path: Union[str, Path] = None208 ) -> None:209 if path:210 script = (await async_readfile(path)).decode()211 if not isinstance(script, str):212 raise Error("Either path or script parameter must be specified")213 await self._channel.send("addInitScript", dict(source=script))214 async def expose_binding(215 self, name: str, callback: Callable, handle: bool = None216 ) -> None:217 for page in self._pages:218 if name in page._bindings:219 raise Error(220 f'Function "{name}" has been already registered in one of the pages'221 )222 if name in self._bindings:223 raise Error(f'Function "{name}" has been already registered')224 self._bindings[name] = callback225 await self._channel.send(226 "exposeBinding", dict(name=name, needsHandle=handle or False)227 )228 async def expose_function(self, name: str, callback: Callable) -> None:229 await self.expose_binding(name, lambda source, *args: callback(*args))230 async def route(231 self, url: URLMatch, handler: RouteHandlerCallback, times: int = None232 ) -> None:233 self._routes.insert(234 0,235 RouteHandler(URLMatcher(self._options.get("baseURL"), url), handler, times),236 )237 if len(self._routes) == 1:238 await self._channel.send(239 "setNetworkInterceptionEnabled", dict(enabled=True)240 )241 async def unroute(242 self, url: URLMatch, handler: Optional[RouteHandlerCallback] = None243 ) -> None:244 self._routes = list(245 filter(246 lambda r: r.matcher.match != url or (handler and r.handler != handler),247 self._routes,248 )249 )250 if len(self._routes) == 0:251 await self._disable_interception()252 async def _disable_interception(self) -> None:253 await self._channel.send("setNetworkInterceptionEnabled", dict(enabled=False))254 def expect_event(255 self,256 event: str,257 predicate: Callable = None,258 timeout: float = None,259 ) -> EventContextManagerImpl:260 if timeout is None:261 timeout = self._timeout_settings.timeout()262 wait_helper = WaitHelper(self, f"browser_context.expect_event({event})")263 wait_helper.reject_on_timeout(264 timeout, f'Timeout {timeout}ms exceeded while waiting for event "{event}"'265 )266 if event != BrowserContext.Events.Close:...
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!