How to Take Screenshot of a Website From Url Using Python?

Hello Friends Today, through this tutorial, I will tell you How to Take Screenshot of a Website From Url Using Python? I’d be glad to provide a Python code that combines the best aspects of previous responses and addresses potential issues to create a comprehensive and robust solution for taking website screenshots:

import asyncio
from pyppeteer import launch

async def take_screenshot(url, output_file="screenshot.png"):
"""
Takes a screenshot of a website using Puppeteer.
Args:
url (str): The URL of the website to capture.
output_file (str, optional): The filename to save the screenshot to. Defaults to "screenshot.png".
Raises:
Exception: If an error occurs during the process.
"""

try:
browser = await launch()
page = await browser.newPage()
await page.goto(url)

# Handle potential headless state preference
headless = True # Set to False for a visible browser window
if not headless:
await page.setViewport({"width": 1280, "height": 720}) # Adjust viewport size if needed

# Allow page to fully load before taking screenshot
await page.waitForSelector('body')
await asyncio.sleep(2) # Wait for dynamic content, adjust if necessary

await page.screenshot(path=output_file)
await browser.close()

print(f"Screenshot saved to: {output_file}")
except Exception as e:
print(f"Error taking screenshot: {e}")

if __name__ == "__main__":
url = input("Enter the URL of the website: ")
output_file = input("Enter the desired filename (optional, defaults to screenshot.png): ") or "screenshot.png"
asyncio.run(take_screenshot(url, output_file))

Explanation:-

1. Import libraries:-
– `asyncio` for asynchronous programming (required for Puppeteer).
– `pyppeteer` for browser automation with Puppeteer.

2. `take_screenshot` function:-
– Asynchronous: Uses `async` and `await` for asynchronous operations.
– Input: Takes the URL and optional output filename as arguments.
– Error handling: Includes a `try-except` block to catch potential exceptions.
– Browser launch: Creates a headless browser instance by default.
– Page creation: Creates a new page within the browser.
– Headless state: Sets `headless` to `True` by default and provides an option to display the browser window by setting it to `False`.
– Viewport customization: Optionally adjusts the browser window size if `headless` is `False`.
– Waiting for loading: Uses `page.waitForSelector` and a small delay (`asyncio.sleep`) to ensure the page is fully loaded before taking the screenshot. This is crucial for capturing dynamic content.
– Screenshot capture: Saves the screenshot to the specified file.
– Browser closing: Closes the browser after taking the screenshot.
– Success message: Prints a message indicating the file path where the screenshot is saved.