Playwright Screenshots
Capture high-fidelity screenshots of any web page using Playwright. Runs headless Chromium from a notebook cell.
References
- Playwright for Python: https://playwright.dev/python/
- Screenshot API: https://playwright.dev/python/docs/screenshots
Requirements
pip install playwrightplaywright install chromium
Configuration
Target URL, viewport dimensions, and output path. Set DEVICE_SCALE_FACTOR to 2 for Retina-quality captures.
In [ ]:
from playwright.async_api import async_playwright # pip install playwright
In [ ]:
URL = "https://www.google.com/" # target url
VIEWPORT_WIDTH = 1280
VIEWPORT_HEIGHT = 800
DEVICE_SCALE_FACTOR = 2
# device_scale_factor=2 renders a 1280x800 CSS viewport to 2560x1600 output pixels
OUTPUT_PATH = "ss-full.png"
FULL_PAGE = False # True = capture entire scrollable page
WAIT_MS = 1500 # ms to wait after network idle
print(f"URL : {URL}")
print(f"Viewport : {VIEWPORT_WIDTH} x {VIEWPORT_HEIGHT}")
print(f"Scale factor : {DEVICE_SCALE_FACTOR}")
print(f"Output : {OUTPUT_PATH}")
print(f"Full page : {FULL_PAGE}")
URL : https://www.google.com/ Viewport : 1280 x 800 Scale factor : 2 Output : ss-full.png Full page : False
Capture screenshot
Launch headless Chromium, navigate to the target URL, wait for the page to settle, and save the screenshot.
In [ ]:
async with async_playwright() as p:
browser = await p.chromium.launch(headless=True)
page = await browser.new_page(
viewport={"width": VIEWPORT_WIDTH, "height": VIEWPORT_HEIGHT},
device_scale_factor=DEVICE_SCALE_FACTOR,
)
await page.goto(URL, wait_until="networkidle")
await page.wait_for_timeout(WAIT_MS)
await page.screenshot(path=OUTPUT_PATH, full_page=FULL_PAGE)
await browser.close()
print(f"Saved: {OUTPUT_PATH}")
Saved: ss-full.png