Take a screenshot of a webpage using Playwright. Args: url (str): The URL to take a screenshot of output_path (str, optional): Path to save the screenshot. If None, saves to a temporary file. width (int, optional): Viewport width. Defaults to 1280. heigh
(url: str, output_path: str = None, width: int = 1280, height: int = 720)
| 7 | from pathlib import Path |
| 8 | |
| 9 | async def take_screenshot(url: str, output_path: str = None, width: int = 1280, height: int = 720) -> str: |
| 10 | """ |
| 11 | Take a screenshot of a webpage using Playwright. |
| 12 | |
| 13 | Args: |
| 14 | url (str): The URL to take a screenshot of |
| 15 | output_path (str, optional): Path to save the screenshot. If None, saves to a temporary file. |
| 16 | width (int, optional): Viewport width. Defaults to 1280. |
| 17 | height (int, optional): Viewport height. Defaults to 720. |
| 18 | |
| 19 | Returns: |
| 20 | str: Path to the saved screenshot |
| 21 | """ |
| 22 | if output_path is None: |
| 23 | # Create a temporary file with .png extension |
| 24 | temp_file = tempfile.NamedTemporaryFile(suffix='.png', delete=False) |
| 25 | output_path = temp_file.name |
| 26 | temp_file.close() |
| 27 | |
| 28 | async with async_playwright() as p: |
| 29 | browser = await p.chromium.launch(headless=True) |
| 30 | page = await browser.new_page(viewport={'width': width, 'height': height}) |
| 31 | |
| 32 | try: |
| 33 | await page.goto(url, wait_until='networkidle') |
| 34 | await page.screenshot(path=output_path, full_page=True) |
| 35 | finally: |
| 36 | await browser.close() |
| 37 | |
| 38 | return output_path |
| 39 | |
| 40 | def take_screenshot_sync(url: str, output_path: str = None, width: int = 1280, height: int = 720) -> str: |
| 41 | """ |
no outgoing calls
no test coverage detected