Best Python code snippet using playwright-python
main.py
Source:main.py
...87 print(item_matches)88 if len(item_matches) > 0:89 # select the closest one90 button_selector = f'(//div[@class="buy-box"])[{item_matches[0][2]}]/*[contains(@class, "button")]'91 button_class_dict: Dict[str, str] = await page.eval_on_selector(92 button_selector,93 '(button) => button.classList',94 )95 if 'custom' not in button_class_dict.values():96 # just click on the button97 await page.click(button_selector, click_count=input.quantity)98 item_title = await page.eval_on_selector(99 '(//div[@class="buy-box"])[1]/div[@class="left"]/p',100 '(title) => title.innerText',101 )102 items.append({'name': item_title, 'quantity': input.quantity})103 else:104 # go into customization105 await page.click(button_selector)106 await page.wait_for_timeout(500)107 # get the first sub-item108 item_title = await page.eval_on_selector(109 '(//h1[@class="title"])[1]',110 '(title) => title.innerText',111 )112 await page.fill('//input[contains(@class, "count")]', str(input.quantity))113 await page.wait_for_timeout(500)114 await page.click('button.to-cart')115 await page.wait_for_timeout(1000)116 await page.goto('https://mcd.cn/product')117 # await page.click('div:text("é¤åèå")')118 items.append({'name': item_title, 'quantity': input.quantity})119 else:120 result_count = await page.eval_on_selector_all(121 '//div[@class="buy-box"]/div[@class="left"]/p',122 '(boxes) => boxes.length',123 )124 # pick one at random125 item_idx = random.sample(range(1, result_count + 1), input.quantity)126 for idx in item_idx:127 button_selector = f'(//div[@class="buy-box"])[{idx}]/*[contains(@class, "button")]'128 button_class_dict: Dict[str, str] = await page.eval_on_selector(129 button_selector,130 '(button) => button.classList',131 )132 if 'custom' not in button_class_dict.values():133 # just click on the button134 await page.click(button_selector, click_count=1)135 item_title = await page.eval_on_selector(136 '(//div[@class="buy-box"])[1]/div[@class="left"]/p',137 '(title) => title.innerText',138 )139 items.append({'name': item_title, 'quantity': 1})140 else:141 # go into customization142 await page.click(button_selector)143 await page.wait_for_timeout(500)144 # get the first sub-item145 item_title = await page.eval_on_selector(146 '(//h1[@class="title"])[1]',147 '(title) => title.innerText',148 )149 await page.fill('//input[contains(@class, "count")]', '1')150 await page.wait_for_timeout(500)151 await page.click('button.to-cart')152 await page.wait_for_timeout(1000)153 items.append({'name': item_title, 'quantity': 1})154 # await page.click('div:text("é¤åèå")')155 await page.goto('https://mcd.cn/product')156 await page.wait_for_timeout(2000)157 await page.fill('//input[contains(@placeholder, "æå¤")]', input.query)158 await page.click('button.ant-input-search-button')159 await page.wait_for_timeout(1000)160 state = 'ordered'161 metadata = {'items': items}162 sessions[session_id] = (session, browser, page, state)163 return SessionOutput(id=session_id, state=state, metadata=metadata)164 except KeyError:165 raise HTTPException(state_code=404, detail='session not found')166@app.post('/sessions/{session_id}/cart/clear', response_model=SessionOutput)167async def clear_session_cart(session_id: str):168 try:169 session, browser, page, state = sessions[session_id]170 await page.click('//div[@class="car"]')171 await page.wait_for_timeout(500)172 await page.click('span:text("æ¸
空è´ç©è½¦")')173 await page.wait_for_timeout(500)174 await page.click('//div[@class="ant-popover-buttons"]/button[contains(@class, "ant-btn-primary")]')175 state = 'cart_cleared'176 sessions[session_id] = (session, browser, page, state)177 return SessionOutput(id=session_id, state=state)178 except KeyError:179 raise HTTPException(state_code=404, detail='session not found')180@app.get('/sessions/{session_id}/cart', response_model=SessionOutput)181async def get_session_cart(session_id: str):182 try:183 session, browser, page, state = sessions[session_id]184 cart_price_texts = await page.eval_on_selector_all(185 '//div[@class="price-info"]/span',186 '(spans) => spans.map((span) => span.innerText)',187 )188 address_texts = await page.eval_on_selector_all(189 '//div[@class="othpart address"]/div[@class="center"]/div',190 '(spans) => spans.map((span) => span.innerText)',191 )192 deliver_time_texts = await page.eval_on_selector_all(193 '//div[@class="othpart time"]/div[@class="center"]/div',194 '(spans) => spans.map((span) => span.innerText)',195 )196 checkout_button_class_dict: Dict[str, str] = await page.eval_on_selector(197 '//button[contains(@class, "to-check")]',198 '(button) => button.classList',199 )200 if 'grey' in checkout_button_class_dict.values():201 state = 'cart_empty'202 sessions[session_id] = (session, browser, page, state)203 return SessionOutput(204 id=session_id,205 state=state,206 metadata={207 'items': [],208 'cart_price_texts': cart_price_texts,209 'address_texts': address_texts,210 'deliver_time_texts': deliver_time_texts,...
test_html_select.py
Source:test_html_select.py
...82 # select / nothing selected ###########################################83 # initial value84 await page.goto(context.make_url('/select/nothing-selected/'))85 await page.wait_for_selector('select')86 selected_options = await page.eval_on_selector('select', GET_OPTIONS)87 assert selected_options == ['foo']88 for attempt in eventually():89 async with attempt:90 assert test_data['select/nothing-selected'] == 'foo'91 # user select92 await page.select_option('select', 'bar')93 selected_options = await page.eval_on_selector('select', GET_OPTIONS)94 assert selected_options == ['bar']95 for attempt in eventually():96 async with attempt:97 assert test_data['select/nothing-selected'] == 'bar'98 # select / pre selected ###############################################99 # initial value100 await page.goto(context.make_url('/select/pre-selected/'))101 await page.wait_for_selector('select')102 selected_options = await page.eval_on_selector('select', GET_OPTIONS)103 assert selected_options == ['bar']104 for attempt in eventually():105 async with attempt:106 assert test_data['select/pre-selected'] == 'bar'107 # user select108 await page.select_option('select', 'foo')109 selected_options = await page.eval_on_selector('select', GET_OPTIONS)110 assert selected_options == ['foo']111 for attempt in eventually():112 async with attempt:113 assert test_data['select/pre-selected'] == 'foo'114 # multi / nothing selected ############################################115 # initial value116 await page.goto(context.make_url('/multi-select/nothing-selected/'))117 await page.wait_for_selector('select')118 selected_options = await page.eval_on_selector('select', GET_OPTIONS)119 assert selected_options == []120 for attempt in eventually():121 async with attempt:122 assert test_data['multi-select/nothing-selected'] == []123 # user select124 await page.select_option('select', ['foo', 'bar'])125 selected_options = await page.eval_on_selector('select', GET_OPTIONS)126 assert selected_options == ['foo', 'bar']127 for attempt in eventually():128 async with attempt:129 assert test_data['multi-select/nothing-selected'] == [130 'foo',131 'bar',132 ]133 # multi / pre selected ################################################134 # initial value135 await page.goto(context.make_url('/multi-select/pre-selected/'))136 await page.wait_for_selector('select')137 selected_options = await page.eval_on_selector('select', GET_OPTIONS)138 assert selected_options == ['foo', 'bar']139 for attempt in eventually():140 async with attempt:141 assert test_data['multi-select/pre-selected'] == ['foo', 'bar']142 # user select143 await page.select_option('select', ['foo', 'baz'])144 selected_options = await page.eval_on_selector('select', GET_OPTIONS)145 assert selected_options == ['foo', 'baz']146 for attempt in eventually():147 async with attempt:148 assert test_data['multi-select/pre-selected'] == [149 'foo',150 'baz',151 ]152 # user deselect153 await page.goto(context.make_url('/multi-select/pre-selected/'))154 await page.wait_for_selector('select')155 await page.select_option('select', [])156 selected_options = await page.eval_on_selector('select', GET_OPTIONS)157 assert selected_options == []158 for attempt in eventually():159 async with attempt:...
test_playwright.py
Source:test_playwright.py
...48 page.goto(f"{self.live_server_url}/")49 page.wait_for_selector(".issues-at-geolocation")50 self.assertIn(51 "/issues/60.6/65/1000",52 page.eval_on_selector(".issues-at-geolocation", "el => el.href"),53 )54 self.assertIn(55 "/issues/60.6/65/1000",56 page.eval_on_selector(".issues-at-map-center", "el => el.href"),57 )58 bounding_box = page.locator("div.leaflet-container").bounding_box()59 page.mouse.move(60 bounding_box["x"] + bounding_box["width"] / 2,61 bounding_box["y"] + bounding_box["height"] / 2,62 steps=5,63 )64 page.mouse.down()65 page.mouse.move(bounding_box["x"] + 100, bounding_box["y"] + 100, steps=5)66 page.mouse.up()67 match = PathMatch(68 page.eval_on_selector(".issues-at-map-center", "el => el.href")69 )70 self.assertAlmostEqual(match.args["latitude"], 60.6, delta=0.01)71 self.assertAlmostEqual(match.args["longitude"], 65, delta=0.01)72 page.close()73 def test_url_for_user_selected_location_is_shown(self):74 page = self.browser_context.new_page()75 c1 = models.CivicPoint.create("foo", geos.Point(60.88, 60.88))76 page.set_default_timeout(5000)77 page.goto(f"{self.live_server_url}/")78 page.focus("input[type=text]")79 page.type("input[type=text]", "foo")80 page.locator("a.dropdown-item").click()81 self.assertIn(82 "/issues/60.88/60.88/1000",83 page.eval_on_selector(".issues-at-named-location", "el => el.href"),84 )85 page.close()86class ListIssuesLiveServerTestCase(StaticLiveServerTestCase):87 playwright: typing.Any88 browser: Browser89 # Copied from https://github.com/mxschmitt/python-django-playwright/blob/master/test_login.py90 @classmethod91 def setUpClass(cls):92 # We will get following error if this is not enabled93 # django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.94 os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true"95 super().setUpClass()96 cls.playwright = sync_playwright().start()97 cls.browser = cls.playwright.firefox.launch()98 cls.browser_context = cls.browser.new_context()99 # cls.browser.set_default_timeout(1000)100 @classmethod101 def tearDownClass(cls):102 super().tearDownClass()103 cls.browser.close()104 cls.playwright.stop()105 def test_recenter_url_is_updated_on_zoom_and_maximum_value_of_100000_meters(self):106 page = self.browser_context.new_page()107 # c1 = models.CivicPoint.create("foo", geos.Point(60.88, 60.88))108 page.set_default_timeout(5000)109 page.goto(110 self.live_server_url + reverse("list_issues", args=(60.6, 60.6, 1000))111 )112 match = PathMatch(page.eval_on_selector(".recenter-map-url", "el => el.href"))113 self.assertAlmostEqual(match.args["latitude"], 60.6, delta=0.01)114 self.assertAlmostEqual(match.args["longitude"], 60.6, delta=0.01)115 self.assertAlmostEqual(match.args["distance"], 1000, delta=10)116 page.locator(".leaflet-control-zoom-out").click()117 time.sleep(0.5)118 match = PathMatch(page.eval_on_selector(".recenter-map-url", "el => el.href"))119 self.assertAlmostEqual(match.args["latitude"], 60.6, delta=0.01)120 self.assertAlmostEqual(match.args["longitude"], 60.6, delta=0.01)121 self.assertNotAlmostEqual(match.args["distance"], 1000, delta=10)122 page.locator(".leaflet-control-zoom-out").click(delay=250, click_count=8)123 match = PathMatch(page.eval_on_selector(".recenter-map-url", "el => el.href"))124 self.assertAlmostEqual(match.args["latitude"], 60.6, delta=0.01)125 self.assertAlmostEqual(match.args["longitude"], 60.6, delta=0.01)126 self.assertEqual(match.args["distance"], 100000)...
test_queryselector.py
Source:test_queryselector.py
...19 # Register another engine after creating context.20 await selectors.register("tag2", tag_selector)21 page = await context.new_page()22 await page.set_content("<div><span></span></div><div></div>")23 assert await page.eval_on_selector("tag=DIV", "e => e.nodeName") == "DIV"24 assert await page.eval_on_selector("tag=SPAN", "e => e.nodeName") == "SPAN"25 assert await page.eval_on_selector_all("tag=DIV", "es => es.length") == 226 assert await page.eval_on_selector("tag2=DIV", "e => e.nodeName") == "DIV"27 assert await page.eval_on_selector("tag2=SPAN", "e => e.nodeName") == "SPAN"28 assert await page.eval_on_selector_all("tag2=DIV", "es => es.length") == 229 # Selector names are case-sensitive.30 with pytest.raises(Error) as exc:31 await page.query_selector("tAG=DIV")32 assert 'Unknown engine "tAG" while parsing selector tAG=DIV' in exc.value.message33 await context.close()34async def test_selectors_register_should_work_with_path(35 selectors, page: Page, utils, assetdir36):37 await utils.register_selector_engine(38 selectors, "foo", path=assetdir / "sectionselectorengine.js"39 )40 await page.set_content("<section></section>")41 assert await page.eval_on_selector("foo=whatever", "e => e.nodeName") == "SECTION"42async def test_selectors_register_should_work_in_main_and_isolated_world(43 selectors, page: Page, utils44):45 dummy_selector_script = """{46 create(root, target) { },47 query(root, selector) {48 return window.__answer;49 },50 queryAll(root, selector) {51 return window['__answer'] ? [window['__answer'], document.body, document.documentElement] : [];52 }53 }"""54 await utils.register_selector_engine(selectors, "main", dummy_selector_script)55 await utils.register_selector_engine(56 selectors, "isolated", dummy_selector_script, content_script=True57 )58 await page.set_content("<div><span><section></section></span></div>")59 await page.evaluate('() => window.__answer = document.querySelector("span")')60 # Works in main if asked.61 assert await page.eval_on_selector("main=ignored", "e => e.nodeName") == "SPAN"62 assert (63 await page.eval_on_selector("css=div >> main=ignored", "e => e.nodeName")64 == "SPAN"65 )66 assert await page.eval_on_selector_all(67 "main=ignored", "es => window.__answer !== undefined"68 )69 assert (70 await page.eval_on_selector_all(71 "main=ignored", "es => es.filter(e => e).length"72 )73 == 374 )75 # Works in isolated by default.76 assert await page.query_selector("isolated=ignored") is None77 assert await page.query_selector("css=div >> isolated=ignored") is None78 # $$eval always works in main, to avoid adopting nodes one by one.79 assert await page.eval_on_selector_all(80 "isolated=ignored", "es => window.__answer !== undefined"81 )82 assert (83 await page.eval_on_selector_all(84 "isolated=ignored", "es => es.filter(e => e).length"85 )86 == 387 )88 # At least one engine in main forces all to be in main.89 assert (90 await page.eval_on_selector(91 "main=ignored >> isolated=ignored", "e => e.nodeName"92 )93 == "SPAN"94 )95 assert (96 await page.eval_on_selector(97 "isolated=ignored >> main=ignored", "e => e.nodeName"98 )99 == "SPAN"100 )101 # Can be chained to css.102 assert (103 await page.eval_on_selector("main=ignored >> css=section", "e => e.nodeName")104 == "SECTION"105 )106async def test_selectors_register_should_handle_errors(selectors, page: Page, utils):107 with pytest.raises(Error) as exc:108 await page.query_selector("neverregister=ignored")109 assert (110 'Unknown engine "neverregister" while parsing selector neverregister=ignored'111 in exc.value.message112 )113 dummy_selector_engine_script = """{114 create(root, target) {115 return target.nodeName;116 },117 query(root, selector) {...
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!!