Best Python code snippet using playwright-python
test_network.py
Source:test_network.py
...431 page.on("request", lambda r: requests.append(r))432 await page.goto(server.PREFIX + "/pptr.png")433 assert requests[0].is_navigation_request()434async def test_set_extra_http_headers_should_work(page, server):435 await page.set_extra_http_headers({"foo": "bar"})436 request = (437 await asyncio.gather(438 server.wait_for_request("/empty.html"),439 page.goto(server.EMPTY_PAGE),440 )441 )[0]442 assert request.getHeader("foo") == "bar"443async def test_set_extra_http_headers_should_work_with_redirects(page, server):444 server.set_redirect("/foo.html", "/empty.html")445 await page.set_extra_http_headers({"foo": "bar"})446 request = (447 await asyncio.gather(448 server.wait_for_request("/empty.html"),449 page.goto(server.PREFIX + "/foo.html"),450 )451 )[0]452 assert request.getHeader("foo") == "bar"453async def test_set_extra_http_headers_should_work_with_extra_headers_from_browser_context(454 browser, server455):456 context = await browser.new_context()457 await context.set_extra_http_headers({"foo": "bar"})458 page = await context.new_page()459 request = (460 await asyncio.gather(461 server.wait_for_request("/empty.html"),462 page.goto(server.EMPTY_PAGE),463 )464 )[0]465 await context.close()466 assert request.getHeader("foo") == "bar"467async def test_set_extra_http_headers_should_override_extra_headers_from_browser_context(468 browser, server469):470 context = await browser.new_context(extra_http_headers={"fOo": "bAr", "baR": "foO"})471 page = await context.new_page()472 await page.set_extra_http_headers({"Foo": "Bar"})473 request = (474 await asyncio.gather(475 server.wait_for_request("/empty.html"),476 page.goto(server.EMPTY_PAGE),477 )478 )[0]479 await context.close()480 assert request.getHeader("foo") == "Bar"481 assert request.getHeader("bar") == "foO"482async def test_set_extra_http_headers_should_throw_for_non_string_header_values(483 page, server484):485 error = None486 try:487 await page.set_extra_http_headers({"foo": 1})488 except Error as exc:489 error = exc...
network.py
Source:network.py
...354 :param max_resource_size: Maximum per-resource size.355 '''356 session = get_session_context('network.set_data_size_limits_for_test')357 return await session.execute(cdp.network.set_data_size_limits_for_test(max_total_size, max_resource_size))358async def set_extra_http_headers(359 headers: Headers360 ) -> None:361 '''362 Specifies whether to always send extra HTTP headers with the requests from this page.363 :param headers: Map with extra HTTP headers.364 '''365 session = get_session_context('network.set_extra_http_headers')366 return await session.execute(cdp.network.set_extra_http_headers(headers))367async def set_request_interception(368 patterns: typing.List[RequestPattern]369 ) -> None:370 '''371Sets the requests to intercept that match the provided patterns and optionally resource types.372Deprecated, please use Fetch.enable instead.373.. deprecated:: 1.3374**EXPERIMENTAL**375:param patterns: Requests matching any of these patterns will be forwarded and wait for the corresponding continueInterceptedRequest call.376.. deprecated:: 1.3377'''378 session = get_session_context('network.set_request_interception')379 return await session.execute(cdp.network.set_request_interception(patterns))380async def set_user_agent_override(...
main.py
Source:main.py
1import os2import sys3import shutil4import argparse5from bowler import Query6methods = [7 ("addInitScript", "add_init_script"),8 ("addScriptTag", "add_script_tag"),9 ("addStyleTag", "add_style_tag"),10 ("bringToFront", "bring_to_front"),11 ("dispatchEvent", "dispatch_event"),12 ("emulateMedia", "emulate_media"),13 ("evalOnSelector", "eval_on_selector"),14 ("evalOnSelectorAll", "eval_on_selector_all"),15 ("evaluateHandle", "evaluate_handle"),16 ("expectDownload", "expect_download"),17 ("expectFileChooser", "expect_file_chooser"),18 ("exposeBinding", "expose_binding"),19 ("exposeFunction", "expose_function"),20 ("newPage", "new_page"),21 ("newContext", "new_context"),22 ("innerHTML", "inner_html"),23 ("innerText", "inner_text"),24 ("setContent", "set_content"),25 ("setDefaultNavigationTimeout", "set_default_navigation_timeout"),26 ("setDefaultTimeout", "set_default_timeout"),27 ("setExtraHTTPHeaders", "set_extra_http_headers"),28 ("setInputFiles", "set_input_files"),29 ("setViewportSize", "set_viewport_size"),30 ("textContent", "text_content"),31 ("viewportSize", "viewport_size"),32 ("waitForEvent", "wait_for_event"),33 ("waitForFunction","wait_for_function"),34 ("waitForLoadState", "wait_for_load_state"),35 ("waitForSelector", "wait_for_selector"),36 ("querySelector", "query_selector"),37 ("querySelectorAll", "query_selector_all"),38 ("waitForTimeout","wait_for_timeout"),39]40class RefactorTool:41 def __init__(self, input, nobackups, show_diffs):42 """43 Args:44 input: path to file to be refactored.45 nobackups: If true no backup '.bak' files will be created for those46 files that are being refactored.47 show_diffs: Should diffs of the refactoring be printed to stdout?48 """49 self.nobackups = nobackups50 self.show_diffs = show_diffs51 self.fn = input52 self.query = Query([self.fn])53 def rename_methods(self):54 for old_name, new_name in methods:55 self.query.select_method(old_name).rename(new_name)56 def fix_imports(self):57 # Fix old style: from playwright import sync_playwright58 self.query.select_module("sync_playwright").select_module("playwright").rename(59 "playwright.sync_api"60 )61 pass62 def output_diffs(self):63 self.query.diff()64 def write_file(self):65 if not self.nobackups:66 # Make a backup before refactor67 backup = self.fn + ".bak"68 if os.path.lexists(backup):69 try:70 os.remove(backup)71 except OSError as err:72 self.log_message("Cannot remove backup %s" % backup)73 try:74 shutil.copyfile(self.fn, backup)75 except OSError as err:76 self.log_message("Cannot copy %s to %s" % (self.fn, backup))77 self.query.write()78 def log_message(self, msg):79 print("Info: " + msg)80 def log_error(self, msg):81 print("Error: " + msg)82def main(args=sys.argv[1:]):83 """Main program.84 Args:85 args: optional; a list of command line arguments. If omitted,86 sys.argv[1:] is used.87 """88 # Set up arg parser89 parser = argparse.ArgumentParser(description="Migrate playwright code to 1.8+")90 parser.add_argument(91 "--no-diffs",92 action="store_true",93 default=False,94 help="Don't show diffs of the refactoring",95 )96 parser.add_argument(97 "-n",98 "--nobackups",99 action="store_true",100 default=False,101 help="Don't write backups for modified files",102 )103 parser.add_argument(104 "-w",105 "--write",106 action="store_true",107 default=False,108 help="Write back modified files",109 )110 parser.add_argument("path", metavar="path", type=str, help="the path to the file")111 args = parser.parse_args()112 fix = RefactorTool(args.path, nobackups=False, show_diffs=(not args.no_diffs))113 fix.fix_imports()114 fix.rename_methods()115 if not args.no_diffs:116 fix.output_diffs()117 if args.write:118 fix.write_file()119if __name__ == "__main__":...
example.py
Source:example.py
...82 context = await mocks(browser)83 page = await context.new_page()84 # Mocking:85 await plugins(page, 5)86 await page.set_extra_http_headers(headers=HEADERS)87 return browser, page88async def main():89 async with async_playwright() as p:90 browser, page = await get_chromium_browser_and_page(p, use_proxy=False)91 await asyncio.sleep(1)92 response = await page.goto(93 url=FINGERPRINT_STUNDZIALT,94 wait_until='networkidle',95 )96 await asyncio.sleep(2)97 await page.screenshot(path="test_playwright.png")98 print("Response status: ", response.status)99if __name__ == '__main__':100 asyncio.run(main())
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!!