take_screenshot.py 1.4 KB
Newer Older
luopl's avatar
luopl committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import os
from playwright.sync_api import sync_playwright
import argparse
from PIL import Image
import time


def take_screenshot(url, output_file="screenshot.png"):
    # Convert local path to file:// URL if it's a file
    if os.path.exists(url):
        url = "file://" + os.path.abspath(url)

    try:
        with sync_playwright() as p:
            # Choose a browser, e.g., Chromium, Firefox, or WebKit
            browser = p.chromium.launch(headless=True, args=["--disable-web-security"])
            page = browser.new_page()

            # Navigate to the URL
            page.goto(url, timeout=60000)
            # page.wait_for_timeout(1000)  # give it 1 second to paint

            # Take the screenshot
            page.screenshot(path=output_file, full_page=True, animations="disabled", timeout=60000)

            browser.close()
    except Exception as e:
        print(f"Failed to take screenshot due to: {e}. Generating a blank image.")
        # Generate a blank image
        img = Image.new("RGB", (1280, 960), color="white")
        img.save(output_file)


if __name__ == "__main__":

    # Initialize the parser
    parser = argparse.ArgumentParser(description="Process two path strings.")

    # Define the arguments
    parser.add_argument("--html", type=str)
    parser.add_argument("--png", type=str)

    # Parse the arguments
    args = parser.parse_args()

    take_screenshot(args.html, args.png)