How to take screenshots with Playwright (Node.js and Python)
Playwright screenshot examples in Node.js and Python: full page, a single element, mobile devices and dark mode, with the common mistakes to avoid.
Playwright, from Microsoft, controls Chromium, Firefox and WebKit with the same code. Its screenshot function covers most needs in one line.
Node.js
import { chromium } from "playwright";
const browser = await chromium.launch();
const page = await browser.newPage({ viewport: { width: 1280, height: 800 } });
await page.goto("https://example.com");
await page.screenshot({ path: "page.png", fullPage: true });
await browser.close();Python
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page(viewport={"width": 1280, "height": 800})
page.goto("https://example.com")
page.screenshot(path="page.png", full_page=True)
browser.close()Only one element
await page.locator("#pricing").screenshot({ path: "pricing.png" });Mobile device and dark mode
import { chromium, devices } from "playwright";
const browser = await chromium.launch();
const context = await browser.newContext({ ...devices["iPhone 13"], colorScheme: "dark" });
const page = await context.newPage();
await page.goto("https://example.com");
await page.screenshot({ path: "iphone-dark.png" });Common mistakes
- Capturing too early: wait for the content you need with
page.waitForSelector()rather than a fixed sleep. - Forgetting
npx playwright install chromiumon the server: the library does not ship the browser. - Running one browser per request: reuse the browser and open a new context per capture.
- Large pages in PNG: use JPEG or WebP with a quality setting for much smaller files.
Without running a browser
ScreenAPI uses Playwright and Chrome under the hood and exposes the same options as URL parameters, so you can skip the install:
curl "https://getscreenapi.com/api/v1/screenshot?url=https://example.com&device=iphone-15-pro&dark_mode=true&format=webp" \
-H "x-api-key: YOUR_KEY" -o iphone-dark.webpMore in the Python guide and the documentation.
100 free captures every month, no credit card.
Get a free key