NewMCP server 1.0.10What changed →

Blog

How to screenshot a website with Python

All posts
guidesscreenshotspython

The most reliable way to screenshot a website from Python is Playwright. It drives a real Chromium, waits for the page properly, and captures the whole scrollable page in one call. Install it and download its browser once:

bash
pip install playwright
playwright install chromium

Save this as screenshot.py and run python screenshot.py https://example.com:

python
import sys
from playwright.sync_api import sync_playwright

url = sys.argv[1] if len(sys.argv) > 1 else "https://example.com"

with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page(viewport={"width": 1280, "height": 800})
    page.goto(url, wait_until="networkidle")
    page.screenshot(path="page.png", full_page=True)
    browser.close()

It writes page.png. full_page=True captures the entire scrollable page rather than the 1280 by 800 window, and wait_until="networkidle" waits until the page has made no network requests for half a second, which covers most pages that fetch their content with JavaScript after they load.

Every script in this guide was run with Playwright 1.65 for Python against live pages and against a small test site built to reproduce each problem described below.

Screenshot one element

Point a locator at the element and screenshot the locator. The image is cropped to the element's box:

python
import sys
from playwright.sync_api import sync_playwright

url = sys.argv[1] if len(sys.argv) > 1 else "https://example.com"

with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page(viewport={"width": 1280, "height": 800})
    page.goto(url, wait_until="networkidle")
    page.locator("p").first.screenshot(path="element.png")
    browser.close()

Any CSS selector works in place of p, such as #pricing or table.results. .first takes the first match; without it, Playwright refuses to screenshot a locator that matches several elements.

Screenshot at phone size

Responsive sites can send phones different markup, not just a narrower layout, so emulate the whole device rather than shrinking the window. Playwright ships device presets:

python
import sys
from playwright.sync_api import sync_playwright

url = sys.argv[1] if len(sys.argv) > 1 else "https://example.com"

with sync_playwright() as p:
    browser = p.chromium.launch()
    context = browser.new_context(**p.devices["iPhone 13"])
    page = context.new_page()
    page.goto(url, wait_until="networkidle")
    page.screenshot(path="phone.png")
    browser.close()

The iPhone 13 preset sets a 390 by 664 viewport at a device scale factor of 3, a mobile user agent and touch support, so phone.png comes out 1170 by 1992 pixels.

Images missing from a full-page screenshot

Most sites load images only when they scroll into view, either with loading="lazy" or with a script that watches the scroll position. A full-page screenshot never scrolls, so those images are never requested. On a test page with 12 lazy-loaded images, the first script in this guide captured none of them.

Scroll through the page first, then wait for the images that scrolling started:

python
import sys
from playwright.sync_api import sync_playwright

url = sys.argv[1] if len(sys.argv) > 1 else "https://example.com"


def scroll_through(page):
    """Scroll one screen at a time so lazy-loaded images start loading, then go back to the top."""
    step = page.viewport_size["height"]
    height = page.evaluate("document.documentElement.scrollHeight")
    for y in range(0, height, step):
        page.evaluate("y => window.scrollTo(0, y)", y)
        page.wait_for_timeout(250)
    page.evaluate("window.scrollTo(0, 0)")


def wait_for_images(page):
    """Return once every image has finished loading or failed."""
    page.evaluate("""() => Promise.all(
        [...document.images]
            .filter((img) => !img.complete)
            .map((img) => new Promise((resolve) => {
                img.addEventListener("load", resolve, { once: true });
                img.addEventListener("error", resolve, { once: true });
            }))
    )""")


with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page(viewport={"width": 1280, "height": 800})
    page.goto(url, wait_until="networkidle")
    scroll_through(page)
    wait_for_images(page)
    page.screenshot(path="page.png", full_page=True)
    browser.close()

This captured all 12 images, including on a version of the page where each image took 1.5 seconds to arrive. The explicit image wait matters: calling page.wait_for_load_state("networkidle") after scrolling looks equivalent, but the page already reached that state before the scroll, so it returned immediately, with 6 of the 12 slow images still loading.

Blank areas, fade-ins and cookie banners

Three more things spoil automated screenshots:

  • Content that arrives late. A dashboard or single-page app may render nothing until its own API call returns. networkidle usually covers it, but it never fires on a page that keeps a connection open, such as a chat widget or a live feed: on such a test page it timed out. Playwright's own documentation marks networkidle as discouraged for this reason. Waiting for an element you know appears once the content is there is faster and does not hang.
  • Animations. A hero that fades in over a second is still invisible when the page is otherwise ready. With the default settings, a fade-in test page came out blank.
  • Overlays. Cookie banners and chat launchers often appear a moment after load, so waiting longer makes them more likely to be in the picture, not less.

This version handles all three:

python
import sys
from playwright.sync_api import sync_playwright

url = sys.argv[1] if len(sys.argv) > 1 else "https://example.com"
ready = sys.argv[2] if len(sys.argv) > 2 else "body"         # an element that exists once content has rendered
hide = sys.argv[3] if len(sys.argv) > 3 else "#cookie-banner"  # what to keep out of the picture

with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page(viewport={"width": 1280, "height": 800})
    page.goto(url)
    page.locator(ready).first.wait_for(state="visible", timeout=15_000)
    page.screenshot(
        path="page.png",
        animations="disabled",
        style=f"{hide} {{ display: none !important; }}",
    )
    browser.close()

Run it as python screenshot.py https://example.com/app "#dashboard h1" "#cookie-banner, .chat-launcher". animations="disabled" fast-forwards finite CSS animations and transitions to their end state, and style applies the CSS only while the screenshot is taken. On the test pages, the faded hero appeared in full and the banner was gone.

Screenshot many URLs

Start the browser once and reuse the page, so a slow or broken URL costs one failure, not the whole run:

python
from playwright.sync_api import sync_playwright

urls = [
    "https://example.com",
    "https://example.org",
]

with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page(viewport={"width": 1280, "height": 800})
    for i, url in enumerate(urls):
        try:
            page.goto(url, wait_until="networkidle", timeout=30_000)
            page.screenshot(path=f"shot-{i}.png", full_page=True)
            print("saved", url)
        except Exception as error:
            print("failed", url, error)
    browser.close()

Without running a browser

Everything above runs Chromium on your machine or server: a browser to install and keep updated, memory to budget, and fonts that may render differently from a desktop. If you would rather make an HTTP call, the domscout screenshot API runs the same kind of capture, including the lazy-image scroll and the overlay hiding:

python
import os
import requests

res = requests.post(
    "https://api.domscout.io/screenshot",
    headers={"x-api-key": os.environ["DOMSCOUT_API_KEY"]},
    json={
        "url": "https://example.com",
        "fullPage": True,
        "lazyScroll": True,
        "hideSelectors": ["#cookie-banner"],
        "format": "png",
        "responseType": "binary",
    },
    timeout=60,
)
if res.status_code != 200:
    raise RuntimeError(f"capture failed: {res.status_code} {res.text}")

with open("page.png", "wb") as f:
    f.write(res.content)

A viewport capture costs 1 credit; fullPage, lazyScroll or both add 1, so this request costs 2. Full-page capture needs the Pro plan or above. A full-page capture with lazyScroll is the heaviest kind of request, so if one answers 504, send it again with "async": true and collect the result as a job. To try a single page without code or an account, use the free website screenshot tool.

Next steps