Best Python code snippet using playwright-python
__main__.py
Source: __main__.py
...30 async with semaphore:31 # create folder for output files32 _path = pathlib.Path(f"{url.replace('/','.')}/")33 _path.mkdir(parents=True, exist_ok=True)34 async with async_playwright() as p:35 browser_type = p.chromium36 browser = await browser_type.launch()37 page = await browser.newPage()38 await page.goto(url, timeout=0)39 # save the offer to PDF file40 fn = "offer.pdf" # I don't know what is your fn41 filepath = _path / fn42 filepath.open("w", encoding="utf-8")43 await page.pdf(format="A4", path=filepath)44 await browser.close()45 async with async_playwright() as p:46 browser_type = p.chromium47 browser = await browser_type.launch(headless=False)48import pathlib49import asyncio50from typing import List, Tuple51import playwright52from playwright import async_playwright53import logging54logging.basicConfig(level=logging.INFO)55logger = logging.getLogger(__package__)56# My inrnet is terribly slow, so I use these variables to limit number of running browsers.57# Otherwise playwright commands fails on timeout or the screenshots are taken when the picture is being loaded.58number_of_running_tasks = 259time_in_ms_between_every_screenshot = 500060async def download(urls: List[str]) -> None:61 semaphore = asyncio.Semaphore(number_of_running_tasks)62 tasks_download_offer = [63 asyncio.create_task(download_offer(url, semaphore)) for url in urls64 ]65 await asyncio.gather(*tasks_download_offer)66async def get_current_image_order(page: playwright) -> Tuple[int, int]:67 number_of_pictures_element = await page.querySelector(68 "//span[contains(@class,'image-order')]"69 )70 number_of_pictures_element_text = await number_of_pictures_element.innerText()71 number_of_pictures_element_text = number_of_pictures_element_text.split("/")72 return (73 int(number_of_pictures_element_text[0]),74 int(number_of_pictures_element_text[1]),75 )76async def download_offer(url: str, semaphore: asyncio.Semaphore) -> None:77 async with semaphore:78 # create folder for output files79 _path = pathlib.Path(f"{url.replace('/','.')}/")80 _path.mkdir(parents=True, exist_ok=True)81 async with async_playwright() as p:82 browser_type = p.chromium83 browser = await browser_type.launch()84 page = await browser.newPage()85 await page.goto(url, timeout=0)86 # save the offer to PDF file87 fn = "offer.pdf" # I don't know what is your fn88 filepath = _path / fn89 filepath.open("w", encoding="utf-8")90 await page.pdf(format="A4", path=filepath)91 await browser.close()92 async with async_playwright() as p:93 browser_type = p.chromium94 browser = await browser_type.launch(headless=False)95 page = await browser.newPage()96 await page.goto(url, timeout=0)97 # click on the main picture98 await page.click(99 "//div[contains(@class,'download-cover')][contains(@ng-click,'showEntity(SHOW_ENTITY.FULLSCREEN)')]",100 timeout=0,101 )102 # get current location in pictures103 current, num_of_pictures = await get_current_image_order(page)104 # shift to the beggining of album105 while current != 1:106 await page.click(...
test_async.py
Source: test_async.py
...8 async def test_visit_elements_page(self) -> None:9 """Test that the Elements page can be navigated to.10 :param page: A Playwright browser page.11 """12 async with async_playwright() as playwright:13 browser = await playwright.chromium.launch()14 page = await browser.new_page()15 await page.goto(f"{base_url}/elements")16 header_text: str = await page.inner_text(".main-header")17 assert "Elements" in header_text18 async def test_collapse_elements_container(self) -> None:19 """Test that the Elements container may be collapsed by a user.20 :param page: A Playwright browser page.21 """22 async with async_playwright() as playwright:23 browser = await playwright.chromium.launch()24 page = await browser.new_page()25 await page.goto(f"{base_url}/elements")26 element_group: ElementHandle = await page.wait_for_selector(27 ".element-group"28 )29 await page.click(".header-right")30 element_list_class: str = await element_group.eval_on_selector(31 ".element-list", "el => el.className"32 )33 assert "show" not in element_list_class34@pytest.mark.asyncio35class TestTextBox:36 user: dict = {37 "name": "Test Tester",38 "email": "test@test.com",39 "currentAddress": "3930 N Pine Grove Ave, Chicago, IL 60613",40 "permanentAddress": "24 Girard St, Rochester, NY 14610",41 }42 async def test_submit_valid_data(self):43 """Test that valid data may be submitted.44 :param page: A Playwright browser page.45 """46 async with async_playwright() as playwright:47 browser = await playwright.chromium.launch()48 page = await browser.new_page()49 await page.goto(f"{base_url}/text-box")50 user_form: ElementHandle = await page.wait_for_selector(51 "#userForm"52 )53 username_field: ElementHandle = await user_form.wait_for_selector(54 "#userName"55 )56 email_field: ElementHandle = await user_form.wait_for_selector(57 "#userEmail"58 )59 current_address_field: ElementHandle = (60 await user_form.wait_for_selector("#currentAddress")61 )62 permanent_address_field: ElementHandle = (63 await user_form.wait_for_selector("#permanentAddress")64 )65 await username_field.fill(self.user["name"])66 await email_field.fill(self.user["email"])67 await current_address_field.fill(self.user["currentAddress"])68 await permanent_address_field.fill(self.user["permanentAddress"])69 await page.click("#submit")70 output_field: ElementHandle = await page.wait_for_selector(71 "#output"72 )73 for key, value in self.user.items():74 ele_value: str = await output_field.eval_on_selector(75 f"#{key}", "el => el.innerText"76 )77 assert value in ele_value78 async def test_error_when_invalid_email(self):79 """Test that invalid data may not be submitted.80 :param page: A Playwright browser page.81 """82 async with async_playwright() as playwright:83 browser = await playwright.chromium.launch()84 page = await browser.new_page()85 await page.goto(f"{base_url}/text-box")86 user_form: ElementHandle = await page.wait_for_selector(87 "#userForm"88 )89 email_field: ElementHandle = await user_form.wait_for_selector(90 "#userEmail"91 )92 await email_field.fill("test")93 await page.click("#submit")94 email_class: str = await user_form.eval_on_selector(95 "#userEmail", "el => el.className"96 )97 assert "field-error" in email_class98@pytest.mark.asyncio99class TestButtons:100 @pytest.mark.parametrize(101 "button_type",102 [103 ("Double Click", "doubleClickMessage"),104 ("Right Click", "rightClickMessage"),105 ("Click", "dynamicClickMessage"),106 ],107 )108 async def test_click_types(self, button_type: fixture):109 """Test that specific click actions provide a result.110 :param button_type: A tuple containing click action and result.111 :param page: A Playwright browser page.112 """113 click_action, result = button_type114 async with async_playwright() as playwright:115 browser = await playwright.chromium.launch()116 page = await browser.new_page()117 await page.goto(f"{base_url}/buttons")118 if click_action == "Double Click":119 await page.dblclick("#doubleClickBtn")120 elif click_action == "Right Click":121 await page.click("#rightClickBtn", button="right")122 else:123 await page.click('button >> text="Click Me"')124 message: ElementHandle = await page.is_visible(f"#{result}")...
main.py
Source: main.py
...5from bs4 import BeautifulSoup as bs678async def main():9 async with async_playwright() as p:10 browser = await p.chromium.launch(headless=False)11 page = await browser.new_page(storage_state='auth.json')12 await page.goto('https://www.instagram.com/explore/tags/alanzoka/')13 time.sleep(6)14 html = await page.content()15 soup = bs(html, 'html.parser')16 link = soup.find_all('img')17 for link in soup.find_all('img'):18 foto = (link.get('src'))19 print(foto)2021 # organizar links com pandas2223 # await page.goto('https://www.instagram.com/explore/tags/duckcute/')2425 time.sleep(5)2627 # await browser.close()282930asyncio.run(main())31=======32import time33import asyncio34from playwright.async_api import async_playwright35from bs4 import BeautifulSoup as bs36async def main():37 async with async_playwright() as p:38 browser = await p.chromium.launch(headless=True)39 page = await browser.new_page(storage_state= 'auth.json')40 await page.goto('https://www.instagram.com/explore/')41 time.sleep(15)42 html = await page.content()43 soup = bs(html, 'html.parser')44 link = soup.find_all('img')45 for link in soup.find_all('img'):46 url = (link.get('src'))47 return url48 # tratar os dados49 print(url)50 51 ...
__init__.py
Source: __init__.py
...6user_data_dir = "./utils/browser/data"7_browser: Optional[Browser] = None8async def init() -> Browser:9 global _browser10 # async with async_playwright() as p:11 # _browser = await p.chromium.launch()12 # print(_browser)13 browser = await async_playwright().start()14 _browser = await browser.chromium.launch_persistent_context(15 user_data_dir,16 headless=True,17 args=[18 f"--disable-extensions-except={path_to_extension}",19 f"--load-extension={path_to_extension}",20 ]21 )22 return _browser23async def get_browser() -> Browser:24 return _browser or await init()25try:26 get_browser()27 logger.info("Chromium Browser initialized")...
Closing a confirm() popup with playwright in python
mouse.up() not working after mouse.move()
Playwright: Get full XPATH of selected element
Why are the values yielded by a pytest fixture and a function called directly different?
How to find partial text using Playwright
Download files with goto in playwright-python
Upgrade python3.8 to 3.10 in Ubuntu Docker image
What is `AttributeError: 'ScrapyPlaywrightDownloadHandler' object has no attribute 'browser' in scrapy-playwright?
sync_playwright().start() seems to hang
How to catch browser dialogs (e.g. "download or open") with Playwright for Python?
You have to write the page.on("dialog", lambda dialog: dialog.accept()) code before you press on button which is generating the popup. Playwright works with the listner so you should first start listner then click on element which is generating the popup.
page.on("dialog", lambda dialog: dialog.accept())
page.locator(#xyz).click() // Element opening alert window
Check out the latest blogs from LambdaTest on this topic:
This article is a part of our Content Hub. For more in-depth resources, check out our content hub on Selenium Locators Tutorial.
Websites and web apps are growing in number day by day, and so are the expectations of people for a pleasant web experience. Even though the World Wide Web (WWW) was invented only in 1989 (32 years back), this technology has revolutionized the world we know back then. The best part is that it has made life easier for us. You no longer have to stand in long queues to pay your bills. You can get that done within a few minutes by visiting their website, web app, or mobile app.
Open MCT is a next-generation mission control framework for data visualization on desktop and mobile devices. It was created at NASA’s Ames Research Center, and NASA uses it to analyze spacecraft mission data.
JavaScript is one of the most widely used programming languages. This popularity invites a lot of JavaScript development and testing frameworks to ease the process of working with it. As a result, numerous JavaScript testing frameworks can be used to perform unit testing.
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!!