How to use emulate_media method in Playwright Python

Best Python code snippet using playwright-python

test_page.py

Source:test_page.py Github

copy

Full Screen

...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(...

Full Screen

Full Screen

feedsdb.py

Source:feedsdb.py Github

copy

Full Screen

...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()...

Full Screen

Full Screen

cli.py

Source:cli.py Github

copy

Full Screen

...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...

Full Screen

Full Screen

main.py

Source:main.py Github

copy

Full Screen

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__":...

Full Screen

Full Screen

Playwright tutorial

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.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Python automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful