Best Python code snippet using playwright-python
test_click.py
Source:test_click.py
...13# limitations under the License.14import asyncio15import pytest16from playwright.async_api import Error, TimeoutError17async def give_it_a_chance_to_click(page):18 for _ in range(5):19 await page.evaluate(20 "() => new Promise(f => requestAnimationFrame(() => requestAnimationFrame(f)))"21 )22async def test_click_the_button(page, server):23 await page.goto(server.PREFIX + "/input/button.html")24 await page.click("button")25 assert await page.evaluate("result") == "Clicked"26async def test_click_svg(page, server):27 await page.set_content(28 """29 <svg height="100" width="100">30 <circle onclick="javascript:window.__CLICKED=42" cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />31 </svg>32 """33 )34 await page.click("circle")35 assert await page.evaluate("window.__CLICKED") == 4236async def test_click_the_button_if_window_node_is_removed(page, server):37 await page.goto(server.PREFIX + "/input/button.html")38 await page.evaluate("() => delete window.Node")39 await page.click("button")40 assert await page.evaluate("() => result") == "Clicked"41async def test_click_on_a_span_with_an_inline_element_inside(page, server):42 await page.set_content(43 """44 <style>45 span::before {46 content: 'q'47 }48 </style>49 <span onclick='javascript:window.CLICKED=42'></span>50 """51 )52 await page.click("span")53 assert await page.evaluate("window.CLICKED") == 4254async def test_click_not_throw_when_page_closes(browser, server):55 context = await browser.new_context()56 page = await context.new_page()57 try:58 await asyncio.gather(59 page.close(),60 page.mouse.click(1, 2),61 )62 except Error:63 pass64 await context.close()65async def test_click_the_button_after_navigation(page, server):66 await page.goto(server.PREFIX + "/input/button.html")67 await page.click("button")68 await page.goto(server.PREFIX + "/input/button.html")69 await page.click("button")70 assert await page.evaluate("() => result") == "Clicked"71async def test_click_the_button_after_a_cross_origin_navigation_(page, server):72 await page.goto(server.PREFIX + "/input/button.html")73 await page.click("button")74 await page.goto(server.CROSS_PROCESS_PREFIX + "/input/button.html")75 await page.click("button")76 assert await page.evaluate("() => result") == "Clicked"77async def test_click_with_disabled_javascript(browser, server):78 context = await browser.new_context(java_script_enabled=False)79 page = await context.new_page()80 await page.goto(server.PREFIX + "/wrappedlink.html")81 async with page.expect_navigation():82 await page.click("a")83 assert page.url == server.PREFIX + "/wrappedlink.html#clicked"84 await context.close()85async def test_click_when_one_of_inline_box_children_is_outside_of_viewport(86 page, server87):88 await page.set_content(89 """90 <style>91 i {92 position: absolute93 top: -1000px94 }95 </style>96 <span onclick='javascript:window.CLICKED = 42;'><i>woof</i><b>doggo</b></span>97 """98 )99 await page.click("span")100 assert await page.evaluate("() => window.CLICKED") == 42101async def test_select_the_text_by_triple_clicking(page, server):102 await page.goto(server.PREFIX + "/input/textarea.html")103 text = "This is the text that we are going to try to select. Let's see how it goes."104 await page.fill("textarea", text)105 await page.click("textarea", click_count=3)106 assert (107 await page.evaluate(108 """() => {109 textarea = document.querySelector('textarea')110 return textarea.value.substring(textarea.selectionStart, textarea.selectionEnd)111 }"""112 )113 == text114 )115async def test_click_offscreen_buttons(page, server):116 await page.goto(server.PREFIX + "/offscreenbuttons.html")117 messages = []118 page.on("console", lambda msg: messages.append(msg.text))119 for i in range(11):120 # We might've scrolled to click a button - reset to (0, 0).121 await page.evaluate("window.scrollTo(0, 0)")122 await page.click(f"#btn{i}")123 assert messages == [124 "button #0 clicked",125 "button #1 clicked",126 "button #2 clicked",127 "button #3 clicked",128 "button #4 clicked",129 "button #5 clicked",130 "button #6 clicked",131 "button #7 clicked",132 "button #8 clicked",133 "button #9 clicked",134 "button #10 clicked",135 ]136async def test_waitFor_visible_when_already_visible(page, server):137 await page.goto(server.PREFIX + "/input/button.html")138 await page.click("button")139 assert await page.evaluate("result") == "Clicked"140async def test_wait_with_force(page, server):141 error = None142 await page.goto(server.PREFIX + "/input/button.html")143 await page.eval_on_selector("button", "b => b.style.display = 'none'")144 try:145 await page.click("button", force=True)146 except Error as e:147 error = e148 assert "Element is not visible" in error.message149 assert await page.evaluate("result") == "Was not clicked"150async def test_wait_for_display_none_to_be_gone(page, server):151 done = list()152 await page.goto(server.PREFIX + "/input/button.html")153 await page.eval_on_selector("button", "b => b.style.display = 'none'")154 async def click():155 await page.click("button", timeout=0)156 done.append(True)157 clicked = asyncio.create_task(click())158 await give_it_a_chance_to_click(page)159 assert await page.evaluate("result") == "Was not clicked"160 assert done == []161 await page.eval_on_selector("button", "b => b.style.display = 'block'")162 await clicked163 assert done == [True]164 assert await page.evaluate("result") == "Clicked"165async def test_wait_for_visibility_hidden_to_be_gone(page, server):166 done = list()167 await page.goto(server.PREFIX + "/input/button.html")168 await page.eval_on_selector("button", "b => b.style.visibility = 'hidden'")169 async def click():170 await page.click("button", timeout=0)171 done.append(True)172 clicked = asyncio.create_task(click())173 await give_it_a_chance_to_click(page)174 assert await page.evaluate("result") == "Was not clicked"175 assert done == []176 await page.eval_on_selector("button", "b => b.style.visibility = 'visible'")177 await clicked178 assert done == [True]179 assert await page.evaluate("result") == "Clicked"180async def test_timeout_waiting_for_display_none_to_be_gone(page, server):181 await page.goto(server.PREFIX + "/input/button.html")182 await page.eval_on_selector("button", "b => b.style.display = 'none'")183 try:184 await page.click("button", timeout=5000)185 except Error as e:186 error = e187 assert "Timeout 5000ms exceeded" in error.message188 assert "waiting for element to be visible, enabled and not moving" in error.message189 assert "element is not visible - waiting" in error.message190async def test_timeout_waiting_for_visbility_hidden_to_be_gone(page, server):191 await page.goto(server.PREFIX + "/input/button.html")192 await page.eval_on_selector("button", "b => b.style.visibility = 'hidden'")193 try:194 await page.click("button", timeout=5000)195 except Error as e:196 error = e197 assert "Timeout 5000ms exceeded" in error.message198 assert "waiting for element to be visible, enabled and not moving" in error.message199 assert "element is not visible - waiting" in error.message200async def test_waitFor_visible_when_parent_is_hidden(page, server):201 done = list()202 await page.goto(server.PREFIX + "/input/button.html")203 await page.eval_on_selector("button", "b => b.parentElement.style.display = 'none'")204 async def click():205 await page.click("button", timeout=0)206 done.append(True)207 clicked = asyncio.create_task(click())208 await give_it_a_chance_to_click(page)209 assert done == []210 await page.eval_on_selector(211 "button", "b => b.parentElement.style.display = 'block'"212 )213 await clicked214 assert done == [True]215 assert await page.evaluate("result") == "Clicked"216async def test_click_wrapped_links(page, server):217 await page.goto(server.PREFIX + "/wrappedlink.html")218 await page.click("a")219 assert await page.evaluate("window.__clicked")220async def test_click_on_checkbox_input_and_toggle(page, server):221 await page.goto(server.PREFIX + "/input/checkbox.html")222 assert await page.evaluate("() => result.check") is None223 await page.click("input#agree")224 assert await page.evaluate("result.check")225 assert await page.evaluate("result.events") == [226 "mouseover",227 "mouseenter",228 "mousemove",229 "mousedown",230 "mouseup",231 "click",232 "input",233 "change",234 ]235 await page.click("input#agree")236 assert await page.evaluate("result.check") is False237async def test_click_on_checkbox_label_and_toggle(page, server):238 await page.goto(server.PREFIX + "/input/checkbox.html")239 assert await page.evaluate("result.check") is None240 await page.click('label[for="agree"]')241 assert await page.evaluate("result.check")242 assert await page.evaluate("result.events") == [243 "click",244 "input",245 "change",246 ]247 await page.click('label[for="agree"]')248 assert await page.evaluate("result.check") is False249async def test_not_hang_with_touch_enabled_viewports(playwright, server, browser):250 iphone_6 = playwright.devices["iPhone 6"]251 context = await browser.new_context(252 viewport=iphone_6["viewport"], has_touch=iphone_6["has_touch"]253 )254 page = await context.new_page()255 await page.mouse.down()256 await page.mouse.move(100, 10)257 await page.mouse.up()258 await context.close()259async def test_scroll_and_click_the_button(page, server):260 await page.goto(server.PREFIX + "/input/scrollable.html")261 await page.click("#button-5")262 assert (263 await page.evaluate("document.querySelector('#button-5').textContent")264 == "clicked"265 )266 await page.click("#button-80")267 assert (268 await page.evaluate("document.querySelector('#button-80').textContent")269 == "clicked"270 )271async def test_double_click_the_button(page, server):272 await page.goto(server.PREFIX + "/input/button.html")273 await page.evaluate(274 """() => {275 window.double = false;276 button = document.querySelector('button');277 button.addEventListener('dblclick', event => window.double = true);278 }"""279 )280 await page.dblclick("button")281 assert await page.evaluate("double")282 assert await page.evaluate("result") == "Clicked"283async def test_click_a_partially_obscured_button(page, server):284 await page.goto(server.PREFIX + "/input/button.html")285 await page.evaluate(286 """() => {287 button = document.querySelector('button');288 button.textContent = 'Some really long text that will go offscreen';289 button.style.position = 'absolute';290 button.style.left = '368px';291 }"""292 )293 await page.click("button")294 assert await page.evaluate("() => window.result") == "Clicked"295async def test_click_a_rotated_button(page, server):296 await page.goto(server.PREFIX + "/input/rotatedButton.html")297 await page.click("button")298 assert await page.evaluate("result") == "Clicked"299async def test_fire_contextmenu_event_on_right_click(page, server):300 await page.goto(server.PREFIX + "/input/scrollable.html")301 await page.click("#button-8", button="right")302 assert (303 await page.evaluate("document.querySelector('#button-8').textContent")304 == "context menu"305 )306async def test_click_links_which_cause_navigation(page, server):307 await page.set_content(f'<a href="{server.EMPTY_PAGE}">empty.html</a>')308 # This await should not hang.309 await page.click("a")310async def test_click_the_button_inside_an_iframe(page, server, utils):311 await page.goto(server.EMPTY_PAGE)312 await page.set_content('<div style="width:100px;height:100px">spacer</div>')313 await utils.attach_frame(page, "button-test", server.PREFIX + "/input/button.html")314 frame = page.frames[1]315 button = await frame.query_selector("button")316 await button.click()317 assert await frame.evaluate("window.result") == "Clicked"318async def test_click_the_button_with_device_scale_factor_set(browser, server, utils):319 context = await browser.new_context(320 viewport={"width": 400, "height": 400}, device_scale_factor=5321 )322 page = await context.new_page()323 assert await page.evaluate("window.devicePixelRatio") == 5324 await page.set_content('<div style="width:100px;height:100px">spacer</div>')325 await utils.attach_frame(page, "button-test", server.PREFIX + "/input/button.html")326 frame = page.frames[1]327 button = await frame.query_selector("button")328 await button.click()329 assert await frame.evaluate("window.result") == "Clicked"330 await context.close()331async def test_click_the_button_with_px_border_with_offset(page, server, is_webkit):332 await page.goto(server.PREFIX + "/input/button.html")333 await page.eval_on_selector("button", "button => button.style.borderWidth = '8px'")334 await page.click("button", position={"x": 20, "y": 10})335 assert await page.evaluate("result") == "Clicked"336 # Safari reports border-relative offsetX/offsetY.337 assert await page.evaluate("offsetX") == 20 + 8 if is_webkit else 20338 assert await page.evaluate("offsetY") == 10 + 8 if is_webkit else 10339async def test_click_the_button_with_em_border_with_offset(page, server, is_webkit):340 await page.goto(server.PREFIX + "/input/button.html")341 await page.eval_on_selector("button", "button => button.style.borderWidth = '2em'")342 await page.eval_on_selector("button", "button => button.style.fontSize = '12px'")343 await page.click("button", position={"x": 20, "y": 10})344 assert await page.evaluate("result") == "Clicked"345 # Safari reports border-relative offsetX/offsetY.346 assert await page.evaluate("offsetX") == 12 * 2 + 20 if is_webkit else 20347 assert await page.evaluate("offsetY") == 12 * 2 + 10 if is_webkit else 10348async def test_click_a_very_large_button_with_offset(page, server, is_webkit):349 await page.goto(server.PREFIX + "/input/button.html")350 await page.eval_on_selector("button", "button => button.style.borderWidth = '8px'")351 await page.eval_on_selector(352 "button", "button => button.style.height = button.style.width = '2000px'"353 )354 await page.click("button", position={"x": 1900, "y": 1910})355 assert await page.evaluate("() => window.result") == "Clicked"356 # Safari reports border-relative offsetX/offsetY.357 assert await page.evaluate("() => offsetX") == 1900 + 8 if is_webkit else 1900358 assert await page.evaluate("() => offsetY") == 1910 + 8 if is_webkit else 1910359async def test_click_a_button_in_scrolling_container_with_offset(360 page, server, is_webkit361):362 await page.goto(server.PREFIX + "/input/button.html")363 await page.eval_on_selector(364 "button",365 """button => {366 container = document.createElement('div');367 container.style.overflow = 'auto';368 container.style.width = '200px';369 container.style.height = '200px';370 button.parentElement.insertBefore(container, button);371 container.appendChild(button);372 button.style.height = '2000px';373 button.style.width = '2000px';374 button.style.borderWidth = '8px';375 }""",376 )377 await page.click("button", position={"x": 1900, "y": 1910})378 assert await page.evaluate("window.result") == "Clicked"379 # Safari reports border-relative offsetX/offsetY.380 assert await page.evaluate("offsetX") == 1900 + 8 if is_webkit else 1900381 assert await page.evaluate("offsetY") == 1910 + 8 if is_webkit else 1910382@pytest.mark.skip_browser("firefox")383async def test_click_the_button_with_offset_with_page_scale(384 browser, server, is_chromium, is_webkit385):386 context = await browser.new_context(387 viewport={"width": 400, "height": 400}, is_mobile=True388 )389 page = await context.new_page()390 await page.goto(server.PREFIX + "/input/button.html")391 await page.eval_on_selector(392 "button",393 """button => {394 button.style.borderWidth = '8px'395 document.body.style.margin = '0'396 }""",397 )398 await page.click("button", position={"x": 20, "y": 10})399 assert await page.evaluate("result") == "Clicked"400 expected = {"x": 28, "y": 18}401 if is_webkit:402 # WebKit rounds up during css -> dip -> css conversion.403 expected = {"x": 29, "y": 19}404 elif is_chromium:405 # Chromium rounds down during css -> dip -> css conversion.406 expected = {"x": 27, "y": 18}407 assert await page.evaluate("pageX") == expected["x"]408 assert await page.evaluate("pageY") == expected["y"]409 await context.close()410async def test_wait_for_stable_position(page, server):411 await page.goto(server.PREFIX + "/input/button.html")412 await page.eval_on_selector(413 "button",414 """button => {415 button.style.transition = 'margin 500ms linear 0s';416 button.style.marginLeft = '200px';417 button.style.borderWidth = '0';418 button.style.width = '200px';419 button.style.height = '20px';420 // Set display to "block" - otherwise Firefox layouts with non-even421 // values on Linux.422 button.style.display = 'block';423 document.body.style.margin = '0';424 }""",425 )426 await page.click("button")427 assert await page.evaluate("window.result") == "Clicked"428 assert await page.evaluate("pageX") == 300429 assert await page.evaluate("pageY") == 10430async def test_timeout_waiting_for_stable_position(page, server):431 await page.goto(server.PREFIX + "/input/button.html")432 button = await page.query_selector("button")433 await button.evaluate(434 """button => {435 button.style.transition = 'margin 5s linear 0s'436 button.style.marginLeft = '200px'437 }"""438 )439 error = None440 try:441 await button.click(timeout=5000)442 except Error as e:443 error = e444 assert "Timeout 5000ms exceeded." in error.message445 assert "waiting for element to be visible, enabled and not moving" in error.message446 assert "element is moving - waiting" in error.message447async def test_wait_for_becoming_hit_target(page, server):448 await page.goto(server.PREFIX + "/input/button.html")449 await page.eval_on_selector(450 "button",451 """button => {452 button.style.borderWidth = '0';453 button.style.width = '200px';454 button.style.height = '20px';455 document.body.style.margin = '0';456 document.body.style.position = 'relative';457 flyOver = document.createElement('div');458 flyOver.className = 'flyover';459 flyOver.style.position = 'absolute';460 flyOver.style.width = '400px';461 flyOver.style.height = '20px';462 flyOver.style.left = '-200px';463 flyOver.style.top = '0';464 flyOver.style.background = 'red';465 document.body.appendChild(flyOver);466 }""",467 )468 clicked = [False]469 async def click():470 await page.click("button")471 clicked.append(True)472 click_promise = asyncio.create_task(click())473 assert clicked == [False]474 await page.eval_on_selector(".flyover", "flyOver => flyOver.style.left = '0'")475 await give_it_a_chance_to_click(page)476 assert clicked == [False]477 await page.eval_on_selector(".flyover", "flyOver => flyOver.style.left = '200px'")478 await click_promise479 assert clicked == [False, True]480 assert await page.evaluate("() => window.result") == "Clicked"481async def test_timeout_waiting_for_hit_target(page, server):482 await page.goto(server.PREFIX + "/input/button.html")483 button = await page.query_selector("button")484 await page.evaluate(485 """() => {486 document.body.style.position = 'relative'487 blocker = document.createElement('div')488 blocker.id = 'blocker';489 blocker.style.position = 'absolute'490 blocker.style.width = '400px'491 blocker.style.height = '20px'492 blocker.style.left = '0'493 blocker.style.top = '0'494 document.body.appendChild(blocker)495 }"""496 )497 error = None498 try:499 await button.click(timeout=5000)500 except TimeoutError as e:501 error = e502 assert "Timeout 5000ms exceeded." in error.message503 assert '<div id="blocker"></div> intercepts pointer events' in error.message504 assert "retrying click action" in error.message505async def test_fail_when_obscured_and_not_waiting_for_hit_target(page, server):506 await page.goto(server.PREFIX + "/input/button.html")507 button = await page.query_selector("button")508 await page.evaluate(509 """() => {510 document.body.style.position = 'relative'511 blocker = document.createElement('div')512 blocker.style.position = 'absolute'513 blocker.style.width = '400px'514 blocker.style.height = '20px'515 blocker.style.left = '0'516 blocker.style.top = '0'517 document.body.appendChild(blocker)518 }"""519 )520 await button.click(force=True)521 assert await page.evaluate("window.result") == "Was not clicked"522async def test_wait_for_button_to_be_enabled(page, server):523 await page.set_content(524 '<button onclick="javascript:window.__CLICKED=true;" disabled><span>Click target</span></button>'525 )526 done = list()527 async def click():528 await page.click("text=Click target")529 done.append(True)530 click_promise = asyncio.create_task(click())531 await give_it_a_chance_to_click(page)532 assert await page.evaluate("() => window.__CLICKED") is None533 assert done == []534 await page.evaluate("document.querySelector('button').removeAttribute('disabled')")535 await click_promise536 assert await page.evaluate("window.__CLICKED")537async def test_timeout_waiting_for_button_to_be_enabled(page, server):538 await page.set_content(539 '<button onclick="javascript:window.__CLICKED=true;" disabled><span>Click target</span></button>'540 )541 error = None542 try:543 await page.click("text=Click target", timeout=3000)544 except TimeoutError as e:545 error = e546 assert await page.evaluate("window.__CLICKED") is None547 assert "Timeout 3000ms exceeded" in error.message548 assert "element is disabled - waiting" in error.message549async def test_wait_for_input_to_be_enabled(page, server):550 await page.set_content(551 '<input onclick="javascript:window.__CLICKED=true;" disabled>'552 )553 done = []554 async def click():555 await page.click("input")556 done.append(True)557 click_promise = asyncio.create_task(click())558 await give_it_a_chance_to_click(page)559 assert await page.evaluate("window.__CLICKED") is None560 assert done == []561 await page.evaluate("document.querySelector('input').removeAttribute('disabled')")562 await click_promise563 assert await page.evaluate("window.__CLICKED")564async def test_wait_for_select_to_be_enabled(page, server):565 await page.set_content(566 '<select onclick="javascript:window.__CLICKED=true;" disabled><option selected>Hello</option></select>'567 )568 done = []569 async def click():570 await page.click("select")571 done.append(True)572 click_promise = asyncio.create_task(click())573 await give_it_a_chance_to_click(page)574 assert await page.evaluate("window.__CLICKED") is None575 assert done == []576 await page.evaluate("document.querySelector('select').removeAttribute('disabled')")577 await click_promise578 assert await page.evaluate("window.__CLICKED")579async def test_click_disabled_div(page, server):580 await page.set_content(581 '<div onclick="javascript:window.__CLICKED=true;" disabled>Click target</div>'582 )583 await page.click("text=Click target")584 assert await page.evaluate("window.__CLICKED")585async def test_climb_dom_for_inner_label_with_pointer_events_none(page, server):586 await page.set_content(587 '<button onclick="javascript:window.__CLICKED=true;"><label style="pointer-events:none">Click target</label></button>'588 )589 await page.click("text=Click target")590 assert await page.evaluate("window.__CLICKED")591async def test_climb_up_to_role_button(page, server):592 await page.set_content(593 '<div role=button onclick="javascript:window.__CLICKED=true;"><div style="pointer-events:none"><span><div>Click target</div></span></div>'594 )595 await page.click("text=Click target")596 assert await page.evaluate("window.__CLICKED")597async def test_wait_for_BUTTON_to_be_clickable_when_it_has_pointer_events_none(598 page, server599):600 await page.set_content(601 '<button onclick="javascript:window.__CLICKED=true;" style="pointer-events:none"><span>Click target</span></button>'602 )603 done = []604 async def click():605 await page.click("text=Click target")606 done.append(True)607 click_promise = asyncio.create_task(click())608 await give_it_a_chance_to_click(page)609 assert await page.evaluate("window.__CLICKED") is None610 assert done == []611 await page.evaluate(612 "document.querySelector('button').style.removeProperty('pointer-events')"613 )614 await click_promise615 assert await page.evaluate("window.__CLICKED")616async def test_wait_for_LABEL_to_be_clickable_when_it_has_pointer_events_none(617 page, server618):619 await page.set_content(620 '<label onclick="javascript:window.__CLICKED=true;" style="pointer-events:none"><span>Click target</span></label>'621 )622 click_promise = asyncio.create_task(page.click("text=Click target"))...
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!!