Best Python code snippet using playwright-python
_page.py
Source: _page.py
...284 @property285 def context(self) -> "BrowserContext":286 return self._browser_context287 async def opener(self) -> Optional["Page"]:288 return from_nullable_channel(await self._channel.send("opener"))289 @property290 def main_frame(self) -> Frame:291 return self._main_frame292 def frame(self, name: str = None, url: URLMatch = None) -> Optional[Frame]:293 matcher = URLMatcher(url) if url else None294 for frame in self._frames:295 if name and frame.name == name:296 return frame297 if url and matcher and matcher.matches(frame.url):298 return frame299 return None300 @property301 def frames(self) -> List[Frame]:302 return self._frames.copy()303 def set_default_navigation_timeout(self, timeout: float) -> None:304 self._timeout_settings.set_navigation_timeout(timeout)305 self._channel.send_no_reply(306 "setDefaultNavigationTimeoutNoReply", dict(timeout=timeout)307 )308 def set_default_timeout(self, timeout: float) -> None:309 self._timeout_settings.set_timeout(timeout)310 self._channel.send_no_reply("setDefaultTimeoutNoReply", dict(timeout=timeout))311 async def query_selector(self, selector: str) -> Optional[ElementHandle]:312 return await self._main_frame.query_selector(selector)313 async def query_selector_all(self, selector: str) -> List[ElementHandle]:314 return await self._main_frame.query_selector_all(selector)315 async def wait_for_selector(316 self,317 selector: str,318 timeout: float = None,319 state: Literal["attached", "detached", "hidden", "visible"] = None,320 ) -> Optional[ElementHandle]:321 return await self._main_frame.wait_for_selector(**locals_to_params(locals()))322 async def is_checked(self, selector: str, timeout: float = None) -> bool:323 return await self._main_frame.is_checked(**locals_to_params(locals()))324 async def is_disabled(self, selector: str, timeout: float = None) -> bool:325 return await self._main_frame.is_disabled(**locals_to_params(locals()))326 async def is_editable(self, selector: str, timeout: float = None) -> bool:327 return await self._main_frame.is_editable(**locals_to_params(locals()))328 async def is_enabled(self, selector: str, timeout: float = None) -> bool:329 return await self._main_frame.is_enabled(**locals_to_params(locals()))330 async def is_hidden(self, selector: str, timeout: float = None) -> bool:331 return await self._main_frame.is_hidden(**locals_to_params(locals()))332 async def is_visible(self, selector: str, timeout: float = None) -> bool:333 return await self._main_frame.is_visible(**locals_to_params(locals()))334 async def dispatch_event(335 self, selector: str, type: str, eventInit: Dict = None, timeout: float = None336 ) -> None:337 return await self._main_frame.dispatch_event(**locals_to_params(locals()))338 async def evaluate(self, expression: str, arg: Serializable = None) -> Any:339 return await self._main_frame.evaluate(expression, arg)340 async def evaluate_handle(341 self, expression: str, arg: Serializable = None342 ) -> JSHandle:343 return await self._main_frame.evaluate_handle(expression, arg)344 async def eval_on_selector(345 self,346 selector: str,347 expression: str,348 arg: Serializable = None,349 ) -> Any:350 return await self._main_frame.eval_on_selector(selector, expression, arg)351 async def eval_on_selector_all(352 self,353 selector: str,354 expression: str,355 arg: Serializable = None,356 ) -> Any:357 return await self._main_frame.eval_on_selector_all(selector, expression, arg)358 async def add_script_tag(359 self,360 url: str = None,361 path: Union[str, Path] = None,362 content: str = None,363 type: str = None,364 ) -> ElementHandle:365 return await self._main_frame.add_script_tag(**locals_to_params(locals()))366 async def add_style_tag(367 self, url: str = None, path: Union[str, Path] = None, content: str = None368 ) -> ElementHandle:369 return await self._main_frame.add_style_tag(**locals_to_params(locals()))370 async def expose_function(self, name: str, callback: Callable) -> None:371 await self.expose_binding(name, lambda source, *args: callback(*args))372 async def expose_binding(373 self, name: str, callback: Callable, handle: bool = None374 ) -> None:375 if name in self._bindings:376 raise Error(f'Function "{name}" has been already registered')377 if name in self._browser_context._bindings:378 raise Error(379 f'Function "{name}" has been already registered in the browser context'380 )381 self._bindings[name] = callback382 await self._channel.send(383 "exposeBinding", dict(name=name, needsHandle=handle or False)384 )385 async def set_extra_http_headers(self, headers: Dict[str, str]) -> None:386 await self._channel.send(387 "setExtraHTTPHeaders", dict(headers=serialize_headers(headers))388 )389 @property390 def url(self) -> str:391 return self._main_frame.url392 async def content(self) -> str:393 return await self._main_frame.content()394 async def set_content(395 self,396 html: str,397 timeout: float = None,398 waitUntil: DocumentLoadState = None,399 ) -> None:400 return await self._main_frame.set_content(**locals_to_params(locals()))401 async def goto(402 self,403 url: str,404 timeout: float = None,405 waitUntil: DocumentLoadState = None,406 referer: str = None,407 ) -> Optional[Response]:408 return await self._main_frame.goto(**locals_to_params(locals()))409 async def reload(410 self,411 timeout: float = None,412 waitUntil: DocumentLoadState = None,413 ) -> Optional[Response]:414 return from_nullable_channel(415 await self._channel.send("reload", locals_to_params(locals()))416 )417 async def wait_for_load_state(418 self, state: DocumentLoadState = None, timeout: float = None419 ) -> None:420 return await self._main_frame.wait_for_load_state(**locals_to_params(locals()))421 async def wait_for_event(422 self, event: str, predicate: Callable = None, timeout: float = None423 ) -> Any:424 async with self.expect_event(event, predicate, timeout) as event_info:425 pass426 return await event_info427 async def go_back(428 self,429 timeout: float = None,430 waitUntil: DocumentLoadState = None,431 ) -> Optional[Response]:432 return from_nullable_channel(433 await self._channel.send("goBack", locals_to_params(locals()))434 )435 async def go_forward(436 self,437 timeout: float = None,438 waitUntil: DocumentLoadState = None,439 ) -> Optional[Response]:440 return from_nullable_channel(441 await self._channel.send("goForward", locals_to_params(locals()))442 )443 async def emulate_media(444 self,445 media: Literal["print", "screen"] = None,446 colorScheme: ColorScheme = None,447 ) -> None:448 await self._channel.send("emulateMedia", locals_to_params(locals()))449 async def set_viewport_size(self, viewportSize: ViewportSize) -> None:450 self._viewport_size = viewportSize451 await self._channel.send("setViewportSize", locals_to_params(locals()))452 @property453 def viewport_size(self) -> Optional[ViewportSize]:454 return self._viewport_size...
_frame.py
Source: _frame.py
...54 def __init__(55 self, parent: ChannelOwner, type: str, guid: str, initializer: Dict56 ) -> None:57 super().__init__(parent, type, guid, initializer)58 self._parent_frame = from_nullable_channel(initializer.get("parentFrame"))59 if self._parent_frame:60 self._parent_frame._child_frames.append(self)61 self._name = initializer["name"]62 self._url = initializer["url"]63 self._detached = False64 self._child_frames: List[Frame] = []65 self._page: "Page"66 self._load_states: Set[str] = set(initializer["loadStates"])67 self._event_emitter = EventEmitter()68 self._channel.on(69 "loadstate",70 lambda params: self._on_load_state(params.get("add"), params.get("remove")),71 )72 self._channel.on(73 "navigated",74 lambda params: self._on_frame_navigated(params),75 )76 def _on_load_state(77 self, add: DocumentLoadState = None, remove: DocumentLoadState = None78 ) -> None:79 if add:80 self._load_states.add(add)81 self._event_emitter.emit("loadstate", add)82 elif remove and remove in self._load_states:83 self._load_states.remove(remove)84 def _on_frame_navigated(self, event: FrameNavigatedEvent) -> None:85 self._url = event["url"]86 self._name = event["name"]87 self._event_emitter.emit("navigated", event)88 if "error" not in event and hasattr(self, "_page") and self._page:89 self._page.emit("framenavigated", self)90 @property91 def page(self) -> "Page":92 return self._page93 async def goto(94 self,95 url: str,96 timeout: float = None,97 waitUntil: DocumentLoadState = None,98 referer: str = None,99 ) -> Optional[Response]:100 return cast(101 Optional[Response],102 from_nullable_channel(103 await self._channel.send("goto", locals_to_params(locals()))104 ),105 )106 def _setup_navigation_wait_helper(self, timeout: float = None) -> WaitHelper:107 wait_helper = WaitHelper(self._loop)108 wait_helper.reject_on_event(109 self._page, "close", Error("Navigation failed because page was closed!")110 )111 wait_helper.reject_on_event(112 self._page, "crash", Error("Navigation failed because page crashed!")113 )114 wait_helper.reject_on_event(115 self._page,116 "framedetached",117 Error("Navigating frame was detached!"),118 lambda frame: frame == self,119 )120 if timeout is None:121 timeout = self._page._timeout_settings.navigation_timeout()122 wait_helper.reject_on_timeout(timeout, f"Timeout {timeout}ms exceeded.")123 return wait_helper124 def expect_navigation(125 self,126 url: URLMatch = None,127 wait_until: DocumentLoadState = None,128 timeout: float = None,129 ) -> EventContextManagerImpl[Response]:130 if not wait_until:131 wait_until = "load"132 if timeout is None:133 timeout = self._page._timeout_settings.navigation_timeout()134 deadline = monotonic_time() + timeout135 wait_helper = self._setup_navigation_wait_helper(timeout)136 matcher = URLMatcher(url) if url else None137 def predicate(event: Any) -> bool:138 # Any failed navigation results in a rejection.139 if event.get("error"):140 return True141 return not matcher or matcher.matches(event["url"])142 wait_helper.wait_for_event(143 self._event_emitter,144 "navigated",145 predicate=predicate,146 )147 async def continuation() -> Optional[Response]:148 event = await wait_helper.result()149 if "error" in event:150 raise Error(event["error"])151 if wait_until not in self._load_states:152 t = deadline - monotonic_time()153 if t > 0:154 await self.wait_for_load_state(state=wait_until, timeout=t)155 if "newDocument" in event and "request" in event["newDocument"]:156 request = from_channel(event["newDocument"]["request"])157 return await request.response()158 return None159 return EventContextManagerImpl(asyncio.create_task(continuation()))160 async def wait_for_load_state(161 self, state: DocumentLoadState = None, timeout: float = None162 ) -> None:163 if not state:164 state = "load"165 if state not in ("load", "domcontentloaded", "networkidle"):166 raise Error("state: expected one of (load|domcontentloaded|networkidle)")167 if state in self._load_states:168 return169 wait_helper = self._setup_navigation_wait_helper(timeout)170 wait_helper.wait_for_event(171 self._event_emitter, "loadstate", lambda s: s == state172 )173 await wait_helper.result()174 async def frame_element(self) -> ElementHandle:175 return from_channel(await self._channel.send("frameElement"))176 async def evaluate(self, expression: str, arg: Serializable = None) -> Any:177 return parse_result(178 await self._channel.send(179 "evaluateExpression",180 dict(181 expression=expression,182 arg=serialize_argument(arg),183 ),184 )185 )186 async def evaluate_handle(187 self, expression: str, arg: Serializable = None188 ) -> JSHandle:189 return from_channel(190 await self._channel.send(191 "evaluateExpressionHandle",192 dict(193 expression=expression,194 arg=serialize_argument(arg),195 ),196 )197 )198 async def query_selector(self, selector: str) -> Optional[ElementHandle]:199 return from_nullable_channel(200 await self._channel.send("querySelector", dict(selector=selector))201 )202 async def query_selector_all(self, selector: str) -> List[ElementHandle]:203 return list(204 map(205 cast(ElementHandle, from_channel),206 await self._channel.send("querySelectorAll", dict(selector=selector)),207 )208 )209 async def wait_for_selector(210 self,211 selector: str,212 timeout: float = None,213 state: Literal["attached", "detached", "hidden", "visible"] = None,214 ) -> Optional[ElementHandle]:215 return from_nullable_channel(216 await self._channel.send("waitForSelector", locals_to_params(locals()))217 )218 async def is_checked(self, selector: str, timeout: float = None) -> bool:219 return await self._channel.send("isChecked", locals_to_params(locals()))220 async def is_disabled(self, selector: str, timeout: float = None) -> bool:221 return await self._channel.send("isDisabled", locals_to_params(locals()))222 async def is_editable(self, selector: str, timeout: float = None) -> bool:223 return await self._channel.send("isEditable", locals_to_params(locals()))224 async def is_enabled(self, selector: str, timeout: float = None) -> bool:225 return await self._channel.send("isEnabled", locals_to_params(locals()))226 async def is_hidden(self, selector: str, timeout: float = None) -> bool:227 return await self._channel.send("isHidden", locals_to_params(locals()))228 async def is_visible(self, selector: str, timeout: float = None) -> bool:229 return await self._channel.send("isVisible", locals_to_params(locals()))...
_browser_context.py
Source: _browser_context.py
...104 self._channel.on(105 "request",106 lambda params: self._on_request(107 from_channel(params["request"]),108 from_nullable_channel(params.get("page")),109 ),110 )111 self._channel.on(112 "response",113 lambda params: self._on_response(114 from_channel(params["response"]),115 from_nullable_channel(params.get("page")),116 ),117 )118 self._channel.on(119 "requestFailed",120 lambda params: self._on_request_failed(121 from_channel(params["request"]),122 params["responseEndTiming"],123 params.get("failureText"),124 from_nullable_channel(params.get("page")),125 ),126 )127 self._channel.on(128 "requestFinished",129 lambda params: self._on_request_finished(130 from_channel(params["request"]),131 from_nullable_channel(params.get("response")),132 params["responseEndTiming"],133 from_nullable_channel(params.get("page")),134 ),135 )136 self._closed_future: asyncio.Future = asyncio.Future()137 self.once(138 self.Events.Close, lambda context: self._closed_future.set_result(True)139 )140 def __repr__(self) -> str:141 return f"<BrowserContext browser={self.browser}>"142 def _on_page(self, page: Page) -> None:143 self._pages.append(page)144 self.emit(BrowserContext.Events.Page, page)145 if page._opener and not page._opener.is_closed():146 page._opener.emit(Page.Events.Popup, page)147 def _on_route(self, route: Route, request: Request) -> None:...
_network.py
Source: _network.py
...34 def __init__(35 self, parent: ChannelOwner, type: str, guid: str, initializer: Dict36 ) -> None:37 super().__init__(parent, type, guid, initializer)38 self._redirected_from: Optional["Request"] = from_nullable_channel(39 initializer.get("redirectedFrom")40 )41 self._redirected_to: Optional["Request"] = None42 if self._redirected_from:43 self._redirected_from._redirected_to = self44 self._failure_text: Optional[str] = None45 self._timing: ResourceTiming = {46 "startTime": 0,47 "domainLookupStart": -1,48 "domainLookupEnd": -1,49 "connectStart": -1,50 "secureConnectionStart": -1,51 "connectEnd": -1,52 "requestStart": -1,53 "responseStart": -1,54 "responseEnd": -1,55 }56 self._headers: Dict[str, str] = parse_headers(self._initializer["headers"])57 @property58 def url(self) -> str:59 return self._initializer["url"]60 @property61 def resource_type(self) -> str:62 return self._initializer["resourceType"]63 @property64 def method(self) -> str:65 return self._initializer["method"]66 @property67 def post_data(self) -> Optional[str]:68 data = self.post_data_buffer69 if not data:70 return None71 return data.decode()72 @property73 def post_data_json(self) -> Optional[Any]:74 post_data = self.post_data75 if not post_data:76 return None77 content_type = self.headers["content-type"]78 if not content_type:79 return None80 if content_type == "application/x-www-form-urlencoded":81 return dict(parse.parse_qsl(post_data))82 return json.loads(post_data)83 @property84 def post_data_buffer(self) -> Optional[bytes]:85 b64_content = self._initializer.get("postData")86 if not b64_content:87 return None88 return base64.b64decode(b64_content)89 @property90 def headers(self) -> Dict[str, str]:91 return self._headers92 async def response(self) -> Optional["Response"]:93 return from_nullable_channel(await self._channel.send("response"))94 @property95 def frame(self) -> "Frame":96 return from_channel(self._initializer["frame"])97 def is_navigation_request(self) -> bool:98 return self._initializer["isNavigationRequest"]99 @property100 def redirected_from(self) -> Optional["Request"]:101 return self._redirected_from102 @property103 def redirected_to(self) -> Optional["Request"]:104 return self._redirected_to105 @property106 def failure(self) -> Optional[str]:107 return self._failure_text...
Playwright error connection refused in docker
playwright-python advanced setup
How to select an input according to a parent sibling label
Error when installing Microsoft Playwright
Trouble waiting for changes to complete that are triggered by Python Playwright `select_option`
Capturing and Storing Request Data Using Playwright for Python
Can Playwright be used to launch a browser instance
Trouble in Clicking on Log in Google Button of Pop Up Menu Playwright Python
Scrapy Playwright get date by clicking button
React locator example
I solved my problem. In fact my docker container (frontend) is called "app" which is also domain name of fronend application. My application is running locally on http. Chromium and geko drivers force httpS connection for some domain names one of which is "app". So i have to change name for my docker container wich contains frontend application.
Check out the latest blogs from LambdaTest on this topic:
The sky’s the limit (and even beyond that) when you want to run test automation. Technology has developed so much that you can reduce time and stay more productive than you used to 10 years ago. You needn’t put up with the limitations brought to you by Selenium if that’s your go-to automation testing tool. Instead, you can pick from various test automation frameworks and tools to write effective test cases and run them successfully.
When it comes to web automation testing, there are a number of frameworks like Selenium, Cypress, PlayWright, Puppeteer, etc., that make it to the ‘preferred list’ of frameworks. The choice of test automation framework depends on a range of parameters like type, complexity, scale, along with the framework expertise available within the team. However, it’s no surprise that Selenium is still the most preferred framework among developers and QAs.
Playwright is a framework that I’ve always heard great things about but never had a chance to pick up until earlier this year. And since then, it’s become one of my favorite test automation frameworks to use when building a new automation project. It’s easy to set up, feature-packed, and one of the fastest, most reliable frameworks I’ve worked with.
The speed at which tests are executed and the “dearth of smartness” in testing are the two major problems developers and testers encounter.
With the rapidly evolving technology due to its ever-increasing demand in today’s world, Digital Security has become a major concern for the Software Industry. There are various ways through which Digital Security can be achieved, Captcha being one of them.Captcha is easy for humans to solve but hard for “bots” and other malicious software to figure out. However, Captcha has always been tricky for the testers to automate, as many of them don’t know how to handle captcha in Selenium or using any other test automation framework.
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!!