Best Python code snippet using playwright-python
test_browser.py
Source:test_browser.py
...166 host.click(pid(f"{result}"))167 else:168 host.click("text='Finished Reading!'")169 for page in players.values():170 page.wait_for_function(js_has_class("buzzer", "btn-success"))171 assert "btn-success" in page.locator(pid("buzzer")).get_attribute("class")172 # Get the _round_status:173 # - 0 -> The first player to buzz gets the correct answer174 # - 1 -> The second player to buzz gets the correct answer175 # - 2 -> The third player to buzz gets the correct answer176 # - 3 -> No player gets the correct answer (the host dimisses)177 _round_status = random.choice(range(4))178 # No one answered179 if _round_status == 3:180 host.click("text='Dismiss'")181 for page in players.values():182 page.wait_for_function(js_has_class("buzzer", "btn-danger"))183 assert "btn-success" not in page.locator(pid("buzzer")).get_attribute("class")184 assert "disabled btn-danger" in page.locator(pid("buzzer")).get_attribute("class")185 else:186 guess_order = random.sample(list(players.items()), k=len(players))187 for index, (name, page) in enumerate(guess_order):188 for (other_name, other_page) in guess_order[:index]:189 assert "btn-success" not in other_page.locator(pid("buzzer")).get_attribute(190 "class"191 )192 assert "disabled btn-danger" in other_page.locator(pid("buzzer")).get_attribute(193 "class"194 )195 page.click(pid("buzzer"))196 host.wait_for_function(js_id_equality("player", name))197 assert host.locator(pid("player")).text_content().strip() == name198 if index != _round_status:199 host.click(pid("incorrect_response"))200 else:201 host.click(pid("correct_response"))202 break203 host.wait_for_timeout(200)204 for name, page in players.items():205 player_score = int(page.locator(pid("score")).text_content().strip())206 board_score = int(board.locator(pid(alex.safe_name(name))).text_content().strip())207 assert player_score == board_score208 host.locator(pid("round_transition")).wait_for(state="visible")209 host.click(pid("start_next_round"))210 host.wait_for_load_state()211 board.wait_for_load_state()212 host.locator(pid("get_wager")).wait_for(state="visible")213 host.click(pid("get_wager"))214 assert not page.locator(pid("show_0")).is_visible()215 reveal_prep = dict()216 for name, page in players.items():217 assert "btn-success" not in host.locator(pid(alex.safe_name(name))).get_attribute("class")218 assert "btn-danger" in host.locator(pid(alex.safe_name(name))).get_attribute("class")219 bg_score = int(page.locator(pid("score")).text_content().strip())220 fg_score = int(page.locator(f"{pid('wager_amount')} >> .score").text_content().strip())221 assert bg_score == fg_score222 wager = (max(fg_score, 1000) // 100) * 100223 page.fill(pid("wager_value"), str(wager))224 page.click("text='Submit!'")225 host.wait_for_function(js_has_class(alex.safe_name(name), "btn-success"))226 assert "btn-success" in host.locator(pid(alex.safe_name(name))).get_attribute("class")227 assert "btn-danger" not in host.locator(pid(alex.safe_name(name))).get_attribute("class")228 reveal_prep[name] = {"pre": fg_score, "wager": wager}229 host.locator(pid("show_0")).wait_for(state="visible")230 host.locator(pid("get_questions")).wait_for(state="visible")231 host.click(pid("get_questions"))232 for name, page in players.items():233 assert "btn-success" not in host.locator(pid(alex.safe_name(name))).get_attribute("class")234 assert "btn-danger" in host.locator(pid(alex.safe_name(name))).get_attribute("class")235 page.fill(pid("question_value"), f"{name}'s answer")236 page.click("text='Submit!'")237 host.wait_for_function(js_has_class(alex.safe_name(name), "btn-success"))238 assert "btn-success" in host.locator(pid(alex.safe_name(name))).get_attribute("class")239 assert "btn-danger" not in host.locator(pid(alex.safe_name(name))).get_attribute("class")240 host.locator(pid("show_responses")).wait_for(state="visible")241 host.click(pid("show_responses"))242 host.locator(pid("final_reveal")).wait_for(state="visible")243 for (name, scoring) in sorted(reveal_prep.items(), key=lambda k: k[1]["pre"]):244 for screen in (host, board):245 host.wait_for_function(js_id_equality("player", name))246 assert screen.locator(pid("player")).text_content() == name247 assert screen.locator(pid("question")).text_content() == f"{name}'s answer"248 assert int(screen.locator(pid("score")).text_content().strip()) == scoring["pre"]249 result = random.choice([("correct_fj", 1), ("incorrect_fj", -1)])250 host.click(pid(f"{result[0]}"))251 final_score = scoring["pre"] + (scoring["wager"] * result[1])252 reveal_prep[name]["final"] = final_score253 assert int(host.locator(pid("amount")).text_content().strip()) == scoring["wager"]254 assert int(host.locator(pid("final_score")).text_content().strip()) == final_score255 assert int(players[name].locator(pid("score")).text_content().strip()) == final_score256 host.click(pid("next"))257 winner = sorted(reveal_prep.items(), key=lambda k: k[1]["final"])[-1]258 for page in (host, board, players[winner[0]]):259 page.wait_for_function("document.location.pathname.indexOf('results') > 0")260 assert page.url.endswith("/results/")261 for page in players.values():...
exists.py
Source:exists.py
...36@do(NvimIO[bool])37def command_exists_not(name: str) -> Do:38 exists = yield command_exists(name)39 return not exists40def wait_for_function(name: str, timeout: int=30, **kw: Any) -> NvimIO[None]:41 return wait_until_valid(name, function_exists, timeout=timeout, desc='appear', **kw)42def wait_for_function_undef(name: str, timeout: int=30) -> NvimIO[None]:43 return wait_until_valid(name, function_exists_not, timeout)44def wait_for_command(name: str, timeout: int=30) -> NvimIO[None]:45 return wait_until_valid(name, command_exists, timeout=timeout, desc='appear')46@do(NvimIO[A])47def command_once_defined(name: str, *args: str, timeout: int=30, verbose: bool=False) -> Do:48 yield wait_for_command(name, timeout=timeout)49 yield nvim_command(name, *args, params=NRParams.cons(verbose=verbose, sync=False))50@do(NvimIO[A])51def call_once_defined(name: str, *args: str, timeout: int=10) -> Do:52 yield wait_for_function(name, timeout=timeout)53 yield nvim_call_function(name, *args)54def wait_until_function_produces(55 target: Any,56 name: str,57 *args: str,58 timeout: int=10,59 interval: float=None,60) -> NvimIO[A]:61 return nvimio_repeat_timeout(62 lambda: N.recover_failure(nvim_call_function(name, *args), N.pure),63 lambda a: a == target,64 f'{name} did not produce `{target}` within {timeout} seconds',65 timeout,66 interval,...
main.py
Source:main.py
...10from odinsynth.rulegen import RuleGeneration11from odinsynth.index import IndexedCorpus12def quit_function():13 thread.interrupt_main()14def wait_for_function(seconds: int, func, *args, **kwargs):15 """16 Tries to return a random surface rule, unless it runs out of time.17 """18 timer = threading.Timer(seconds, quit_function)19 timer.start()20 try:21 return func(*args, **kwargs)22 except KeyboardInterrupt:23 return None24 finally:25 timer.cancel()26def validate_query(query):27 if query is None:28 return False29 if isinstance(query, RepeatSurface) and query.min == 0:30 # e.g. [word=car]?31 return False32 if (isinstance(query, TokenSurface)33 and isinstance(query.constraint, NotConstraint)34 and isinstance(query.constraint.constraint, FieldConstraint)):35 # e.g. [!word=car]36 return False37 return True38if __name__ == '__main__':39 # command line arguments40 parser = argparse.ArgumentParser()41 parser.add_argument('--out-dir', type=Path)42 parser.add_argument('--data-dir', type=Path, default=Path('/media/data1/odinsynth'))43 parser.add_argument('--mini-data-dir', type=Path, default=Path('/media/data1/odinsynth-mini'))44 parser.add_argument('--hybrid', action='store_true')45 parser.add_argument('--num-queries', type=int, default=10)46 parser.add_argument('--num-matches', type=int, default=100)47 args = parser.parse_args()48 # ensure output dir exists49 if not args.out_dir.exists():50 args.out_dir.mkdir()51 # start system52 gw = OdinsonGateway.launch(javaopts=['-Xmx10g'])53 gen = RuleGeneration.from_data_dir(args.mini_data_dir, gw)54 gen_rule = gen.random_hybrid_rule if args.hybrid else gen.random_surface_rule55 corpus = IndexedCorpus.from_data_dir(args.data_dir, gw)56 # generate queries57 for i in range(args.num_queries):58 print(f'{i+1}/{args.num_queries}')59 print(' generating random query')60 query = gen_rule()61 print(' query:', query)62 if not validate_query(query):63 print(' rejected')64 continue65 print(' searching')66 data = wait_for_function(5, corpus.get_results, query, args.num_matches)67 if data is None:68 print(' timeout')69 continue70 print(f' {data["num_matches"]} sentences found')71 if data['num_matches'] > 0:72 print(' saving results')73 with open(args.out_dir/f'query_{uuid.uuid4()}.json', 'w') as f:...
test_slider_action.py
Source:test_slider_action.py
...33 page.wait_for_selector("#slider1")34 page.fill("#slider1 input", "20")35 function_evaluated = True36 try:37 page.wait_for_function("document.querySelector('#text1').innerText !== '10'")38 except Exception as e:39 function_evaluated = False40 logging.getLogger().debug(f"Function evaluation timeout.\n{e}")41 if function_evaluated:42 text1_2 = page.query_selector("#text1")43 assert text1_2.inner_text() == "20"44@pytest.mark.teste2e45def test_slider_action_on_change(page: "Page", gui: Gui, helpers):46 d = {"v1": 10, "v2": 10}47 def on_change(state, var, val):48 if var == "d.v2":49 d = {"v1": 2 * val, "v2": val}50 state.d.update(d)51 page_md = """52Value: <|{d.v1}|id=text1|>53Slider: <|{d.v2}|slider|id=slider1|>54"""55 gui._set_frame(inspect.currentframe())56 gui.add_page(name="test", page=page_md)57 helpers.run_e2e(gui)58 page.goto("/test")59 page.expect_websocket()60 page.wait_for_selector("#text1")61 text1 = page.query_selector("#text1")62 assert text1.inner_text() == "10"63 page.wait_for_selector("#slider1")64 page.fill("#slider1 input", "20")65 function_evaluated = True66 try:67 page.wait_for_function("document.querySelector('#text1').innerText !== '10'")68 except Exception as e:69 function_evaluated = False70 logging.getLogger().debug(f"Function evaluation timeout.\n{e}")71 if function_evaluated:72 text1_2 = page.query_selector("#text1")...
Playwright Python: Click random list item from unordered list dropdown
Using Opera, Safari, Brave with playwright
download csv generated file with Playwright
How to expect attribute value with timeout using Playwright
In Playwright for Python, how do I retrieve a handle for elements from within an frame (iframe)?
Headless doesn't work using Playwright and BeautifulSoup 4
Using playwright for python, how can I click a button?
How to take a screenshot of a reddit post using playwright?
Python-Playwright: Is there a way to introspect and/or run commands interactively?
how do I select element in nest html by playwright
Playwright handle differently with elements than the older python browsers...
in dropdown you should page.select_option(selector)
that's also why in Playwright you can't click a check box, you should page.check(selector) https://playwright.dev/python/docs/api/class-page#page-select-option
Check out the latest blogs from LambdaTest on this topic:
The sky’s the limit (and even beyond that) when you want to run test automation. Technology has developed so much that you can reduce time and stay more productive than you used to 10 years ago. You needn’t put up with the limitations brought to you by Selenium if that’s your go-to automation testing tool. Instead, you can pick from various test automation frameworks and tools to write effective test cases and run them successfully.
It’s essential to test all components of your website to see if they work as expected. Playwright’s end to end testing capability helps you achieve this easily. However, if you’re comfortable using Python, you can pair it with the Playwright testing framework to run Python end to end testing on your website.
The year 2021 can be encapsulated as one major transition. In 2022, the current breakthroughs in the elusive fight to eliminate the COVID-19 pandemic are top of mind for enterprises globally. At the same time, we are witnessing recent strides in technological advancements as the world gets digitized. As a result, the year 2022 will see the resumption of massive changes in technology and digital transformation, driving firms to adapt and transform themselves perpetually.
This article is a part of our Content Hub. For more in-depth resources, check out our content hub on Selenium Locators 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.
Get 100 minutes of automation test minutes FREE!!