Best Python code snippet using playwright-python
test_page.py
Source:test_page.py
...966async def test_should_emulate_reduced_motion(page, server):967 assert await page.evaluate(968 "matchMedia('(prefers-reduced-motion: no-preference)').matches"969 )970 await page.emulate_media(reduced_motion="reduce")971 assert await page.evaluate("matchMedia('(prefers-reduced-motion: reduce)').matches")972 assert not await page.evaluate(973 "matchMedia('(prefers-reduced-motion: no-preference)').matches"974 )975 await page.emulate_media(reduced_motion="no-preference")976 assert not await page.evaluate(977 "matchMedia('(prefers-reduced-motion: reduce)').matches"978 )979 assert await page.evaluate(980 "matchMedia('(prefers-reduced-motion: no-preference)').matches"981 )982async def test_input_value(page: Page, server: Server):983 await page.goto(server.PREFIX + "/input/textarea.html")984 await page.fill("input", "my-text-content")985 assert await page.input_value("input") == "my-text-content"986 await page.fill("input", "")987 assert await page.input_value("input") == ""988async def test_drag_and_drop_helper_method(page: Page, server: Server):989 await page.goto(server.PREFIX + "/drag-n-drop.html")990 await page.drag_and_drop("#source", "#target")991 assert (992 await page.eval_on_selector(993 "#target", "target => target.contains(document.querySelector('#source'))"994 )995 is True996 )997async def test_drag_and_drop_with_position(page: Page, server: Server):998 await page.goto(server.EMPTY_PAGE)999 await page.set_content(1000 """1001 <div style="width:100px;height:100px;background:red;" id="red">1002 </div>1003 <div style="width:100px;height:100px;background:blue;" id="blue">1004 </div>1005 """1006 )1007 events_handle = await page.evaluate_handle(1008 """1009 () => {1010 const events = [];1011 document.getElementById('red').addEventListener('mousedown', event => {1012 events.push({1013 type: 'mousedown',1014 x: event.offsetX,1015 y: event.offsetY,1016 });1017 });1018 document.getElementById('blue').addEventListener('mouseup', event => {1019 events.push({1020 type: 'mouseup',1021 x: event.offsetX,1022 y: event.offsetY,1023 });1024 });1025 return events;1026 }1027 """1028 )1029 await page.drag_and_drop(1030 "#red",1031 "#blue",1032 source_position={"x": 34, "y": 7},1033 target_position={"x": 10, "y": 20},1034 )1035 assert await events_handle.json_value() == [1036 {"type": "mousedown", "x": 34, "y": 7},1037 {"type": "mouseup", "x": 10, "y": 20},1038 ]1039async def test_should_check_box_using_set_checked(page: Page):1040 await page.set_content("`<input id='checkbox' type='checkbox'></input>`")1041 await page.set_checked("input", True)1042 assert await page.evaluate("checkbox.checked") is True1043 await page.set_checked("input", False)1044 assert await page.evaluate("checkbox.checked") is False1045async def test_should_set_bodysize_and_headersize(page: Page, server: Server):1046 await page.goto(server.EMPTY_PAGE)1047 async with page.expect_request("*/**") as request_info:1048 await page.evaluate(1049 "() => fetch('./get', { method: 'POST', body: '12345'}).then(r => r.text())"1050 )1051 request = await request_info.value1052 sizes = await request.sizes()1053 assert sizes["requestBodySize"] == 51054 assert sizes["requestHeadersSize"] >= 3001055async def test_should_set_bodysize_to_0(page: Page, server: Server):1056 await page.goto(server.EMPTY_PAGE)1057 async with page.expect_request("*/**") as request_info:1058 await page.evaluate("() => fetch('./get').then(r => r.text())")1059 request = await request_info.value1060 sizes = await request.sizes()1061 assert sizes["requestBodySize"] == 01062 assert sizes["requestHeadersSize"] >= 2001063@pytest.mark.skip_browser("webkit") # https://bugs.webkit.org/show_bug.cgi?id=2252811064async def test_should_emulate_forced_colors(page):1065 assert await page.evaluate("matchMedia('(forced-colors: none)').matches")1066 await page.emulate_media(forced_colors="none")1067 assert await page.evaluate("matchMedia('(forced-colors: none)').matches")1068 assert not await page.evaluate("matchMedia('(forced-colors: active)').matches")1069 await page.emulate_media(forced_colors="active")1070 assert await page.evaluate("matchMedia('(forced-colors: active)').matches")1071 assert not await page.evaluate("matchMedia('(forced-colors: none)').matches")1072async def test_should_not_throw_when_continuing_while_page_is_closing(1073 page: Page, server: Server1074):1075 done = None1076 def handle_route(route: Route) -> None:1077 nonlocal done1078 done = asyncio.gather(route.continue_(), page.close())1079 await page.route("**/*", handle_route)1080 with pytest.raises(Error):1081 await page.goto(server.EMPTY_PAGE)1082 await done1083async def test_should_not_throw_when_continuing_after_page_is_closed(...
feedsdb.py
Source:feedsdb.py
...212 }213 }''')214 mediatype = spec.pop('mediatype', None)215 if mediatype is not None:216 await page.emulate_media(media = mediatype)217 await page.wait_for_timeout(500)218 await page.pdf(**spec)219 async def get_pdf(browser, spec):220 context_opts = dict(221 accept_downloads = True,222 java_script_enabled = False,223 color_scheme = 'light'224 )225 if 'useragent' in spec:226 context_opts['user_agent'] = spec.pop('useragent')227 if 'viewport' in spec:228 context_opts['viewport'] = spec.pop('viewport')229 context = await browser.new_context(**context_opts)230 page = await context.new_page()...
cli.py
Source:cli.py
...313 }314 if output != "-":315 kwargs["path"] = output316 if media_screen:317 page.emulate_media(media="screen")318 pdf = page.pdf(**kwargs)319 if output == "-":320 sys.stdout.buffer.write(pdf)321 else:322 click.echo(323 "Screenshot of '{}' written to '{}'".format(url, output), err=True324 )325 browser.close()326@cli.command()327def install():328 """329 Install Playwright browser needed by this tool.330 Usage:331 shot-scraper install...
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__":...
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!!