Skip to content
GUIDE · SCREENSHOTS

Playwright Screenshots: Full Page, Element, On Failure and Visual Comparison

How to take screenshots in Playwright with Python, JavaScript/TypeScript, Java and C#: viewport, full page, single elements, clipping, JPEG and WebP, masks, retina resolution, automatic screenshots when tests fail, and screenshot comparison.

Last updated

Short answer

Call page.screenshot(path='shot.png') for the visible viewport. Add full_page=True in Python (fullPage: true in JavaScript) to capture the whole scrollable page, or use page.locator('#hero').screenshot() for a single element. Options cover clipping, JPEG and WebP quality, transparency, masks and frozen animations. In Playwright Test, screenshot: 'only-on-failure' saves one whenever a test fails.

Playwright has two screenshot methods, page.screenshot() for the page and locator.screenshot() for one element, plus a test-runner assertion, toHaveScreenshot(), for comparing screenshots between runs. They work the same way in Chromium, Firefox and WebKit, and the options have the same names in every language apart from casing. This guide shows each in Python, JavaScript/TypeScript, Java and C#, then covers what actually goes wrong: half-captured full pages, lazy images, flaky diffs, and blurry output. It was checked against the Playwright 1.65 docs in November 2026.

How to take a screenshot in Playwright

Python

Install with pip install playwright, then playwright install chromium. The sync API is the simplest:

screenshot.py
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="viewport.png")                # what's visible
    page.screenshot(path="full.png", full_page=True)    # the whole scrollable page
    page.locator("h1").screenshot(path="heading.png")   # one element

    png_bytes = page.screenshot()                       # bytes, nothing written to disk
    browser.close()

In async code (FastAPI, aiohttp, Jupyter) use the async API instead. The calls are identical, with await in front:

screenshot_async.py
import asyncio
from playwright.async_api import async_playwright

async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch()
        page = await browser.new_page()
        await page.goto("https://example.com")
        await page.screenshot(path="full.png", full_page=True)
        await browser.close()

asyncio.run(main())

JavaScript and Node.js

screenshot.mjs
// screenshot.mjs  (npm install playwright && npx playwright install chromium)
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: "viewport.png" });
await page.screenshot({ path: "full.png", fullPage: true });
await page.locator("h1").screenshot({ path: "heading.png" });

const buffer = await page.screenshot(); // a Buffer, e.g. to upload to S3
await browser.close();

TypeScript with Playwright Test

Inside a test, use the page fixture and write files under testInfo.outputPath() so they land in the run's output folder, or attach them to the HTML report:

home.spec.ts
// tests/home.spec.ts
import { test } from "@playwright/test";

test("homepage screenshot", async ({ page }, testInfo) => {
  await page.goto("https://example.com");

  // Saved under test-results/, next to traces and videos
  await page.screenshot({ path: testInfo.outputPath("home.png"), fullPage: true });

  // Or attach it to the HTML report
  await testInfo.attach("home", { body: await page.screenshot(), contentType: "image/png" });
});

Java

Screenshots.java
// Maven: com.microsoft.playwright:playwright:1.65.1
import com.microsoft.playwright.*;
import java.nio.file.Paths;

public class Screenshots {
  public static void main(String[] args) {
    try (Playwright playwright = Playwright.create()) {
      Browser browser = playwright.chromium().launch();
      Page page = browser.newPage();
      page.navigate("https://example.com");

      page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("viewport.png")));
      page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("full.png")).setFullPage(true));
      page.locator("h1").screenshot(new Locator.ScreenshotOptions().setPath(Paths.get("heading.png")));

      byte[] buffer = page.screenshot();
    }
  }
}

C# (.NET)

Program.cs
// dotnet add package Microsoft.Playwright
using Microsoft.Playwright;

using var playwright = await Playwright.CreateAsync();
await using var browser = await playwright.Chromium.LaunchAsync();
var page = await browser.NewPageAsync();
await page.GotoAsync("https://example.com");

await page.ScreenshotAsync(new() { Path = "viewport.png" });
await page.ScreenshotAsync(new() { Path = "full.png", FullPage = true });
await page.Locator("h1").ScreenshotAsync(new() { Path = "heading.png" });

byte[] buffer = await page.ScreenshotAsync();

Every variant returns the image bytes (bytes, Buffer, byte[]), whether or not you pass a path. That's handy for uploading to object storage or comparing in memory without touching the disk. When you pass a path, the format is inferred from its extension.

Playwright screenshot options

From the page.screenshot() reference, Playwright 1.65. Java uses setters (setFullPage(true)), C# uses properties (FullPage = true).
PythonJavaScript / TypeScriptDefaultWhat it does
pathpathnoneWhere to save. The image type is inferred from the extension.
full_pagefullPageFalseCapture the full scrollable page instead of the viewport.
clipclipnoneCapture only a rectangle: x, y, width, height.
typetypepngpng, jpeg or webp (WebP since Playwright 1.62).
qualityqualityJPEG 80, WebP 1000–100. Not for PNG. WebP at 100 is lossless.
omit_backgroundomitBackgroundFalseDrop the default white background for transparency. Not for JPEG.
animationsanimationsallowdisabled fast-forwards finite CSS animations and transitions and cancels infinite ones.
caretcarethideHide the blinking text cursor, or keep it with initial.
maskmasknoneList of locators to paint over with a solid box.
mask_colormaskColor#FF00FFColor of the mask boxes (since 1.35).
stylestylenoneCSS applied only while capturing; it pierces shadow DOM and iframes (since 1.41).
scalescaledevicecss gives one image pixel per CSS pixel, regardless of device scale factor.

Playwright full page screenshots (Python and JavaScript)

full_page=True captures the page as if the viewport were tall enough to show all of it, so you don't need to scroll and stitch. On most pages it just works. When it doesn't, it's almost always one of three causes.

Lazy-loaded images show up blank

Images with loading="lazy" or an IntersectionObserver only load when they come near the viewport, and a full-page capture doesn't scroll. Scroll through the page first, then capture:

full_page_lazy.py
page.goto("https://example.com/blog", wait_until="load")

# Scroll down one screen at a time so lazy-loaded images start loading
page.evaluate("""async () => {
  for (let y = 0; y < document.body.scrollHeight; y += window.innerHeight) {
    window.scrollTo(0, y);
    await new Promise((r) => setTimeout(r, 200));
  }
  window.scrollTo(0, 0);
}""")
page.wait_for_load_state("networkidle")

page.screenshot(path="full.png", full_page=True)

Only one screen is captured

Many single-page apps fix html and body to the viewport height and scroll inside a container like #app or main. The document itself is then only one screen tall, so that's all full_page can capture. Let the document grow before taking the shot:

full_page_container.py
# The app scrolls inside a container, so full_page only sees one screen.
# Let the document grow to the content's height before capturing.
page.add_style_tag(content="html, body, #app { height: auto !important; overflow: visible !important; }")
page.screenshot(path="full.png", full_page=True)

Swap #app for your app's scroll container (find it in DevTools: it's the element with overflow: auto or scroll whose scroll bar moves).

Sticky headers and pop-ups get in the way

Fixed and sticky elements, chat widgets and cookie banners render wherever they sit in the layout and can cover content. Hide them for the capture with the style option (shown below) instead of changing your page.

Playwright screenshot of an element

locator.screenshot() crops the capture to one element. It waits for the element to be visible and stable, scrolls it into view, then captures its bounding box. That makes it more robust than calculating coordinates yourself:

element.py
# Waits until the element is visible and stable, then scrolls it into view
page.locator("#pricing").screenshot(path="pricing.png")
page.get_by_role("navigation").screenshot(path="nav.png")
page.get_by_test_id("revenue-chart").screenshot(path="chart.png")

# A fixed region instead of an element (CSS pixels)
page.screenshot(path="region.png", clip={"x": 0, "y": 0, "width": 800, "height": 400})
  • Any locator works: CSS (page.locator('#pricing')), role (get_by_role), test id (get_by_test_id), or text. Locator screenshots accept the same type, quality, mask, style, animations and omit_background options; full_page and clip are page-only.
  • If another element covers yours (a sticky header, a modal), it's covered in the screenshot too. Playwright clips the page image; it doesn't render the element on its own.
  • If the element is itself a scroll container, you get only the part that's currently scrolled into view.
  • If the locator matches several elements, strict mode throws. Narrow it, or pick one with .first or .nth(i).
  • In JavaScript it's await page.locator('#pricing').screenshot({ path: 'pricing.png' }); in Java, locator.screenshot(new Locator.ScreenshotOptions().setPath(...)).

JPEG, WebP, quality and transparent backgrounds

formats.py
page.screenshot(path="shot.jpg", type="jpeg", quality=80)    # smaller, no transparency
page.screenshot(path="shot.webp", type="webp", quality=80)   # Playwright 1.62+; 100 = lossless
page.locator(".logo").screenshot(path="logo.png", omit_background=True)  # transparent PNG

PNG is lossless and the default, which is right for test artifacts and diffs. JPEG and WebP at quality 70–85 are usually much smaller, which matters if you store thousands of captures. Transparency needs PNG (or WebP), and the page itself must leave the area transparent: if html or body has a background color, that color is in the image.

Stable screenshots: animations, masks and injected CSS

Screenshots taken mid-animation, with live timestamps, or with a random avatar differ on every run. That's annoying in a report and fatal in a visual test. Four options deal with it:

stable.py
page.screenshot(
    path="dashboard.png",
    full_page=True,
    animations="disabled",    # finish CSS animations and transitions first
    caret="hide",             # the default: no blinking text cursor
    mask=[page.locator(".timestamp"), page.get_by_test_id("avatar")],
    mask_color="#000000",     # default is pink #FF00FF
    style="#cookie-banner, .chat-widget { display: none !important; }",
)
  • animations="disabled" finishes finite CSS animations and transitions and resets infinite ones, so a fading hero doesn't come out half transparent.
  • mask paints a solid box over each matched element. Use it for content that legitimately changes, such as dates, prices or ads. Masks also apply to invisible matches, so keep locators specific.
  • style injects CSS for the capture only, the cleanest way to hide banners and widgets without touching the page.
  • JavaScript-driven animations (canvas, requestAnimationFrame) aren't affected by animations. Wait for an end state with wait_for_function, or turn the animation off in your app for test builds.

Screenshot resolution: viewport, device scale and scale

Image size is the viewport size times the device scale factor. The default viewport is 1280 × 720 at a scale factor of 1, which looks soft on high-density displays. Set both on the browser context:

resolution.py
context = browser.new_context(
    viewport={"width": 1280, "height": 800},
    device_scale_factor=2,        # "retina": the PNG comes out 2560 x 1600
)
page = context.new_page()
page.goto("https://example.com")
page.screenshot(path="retina.png")
page.screenshot(path="1x.png", scale="css")   # one image pixel per CSS pixel: 1280 x 800

# Phone-sized capture with a built-in device profile
iphone = browser.new_context(**p.devices["iPhone 13"])

scale='css' is useful when you want consistent pixel dimensions across machines (for example, a 1280-pixel-wide image for docs) while keeping a high-density context for everything else. In JavaScript the context options are viewport and deviceScaleFactor, and device profiles come from devices exported by playwright.

Playwright capture screenshot on failure

Playwright Test (JavaScript and TypeScript)

Automatic screenshots are a config switch. only-on-failure keeps the output folder small; on-first-failure captures only the first failing attempt when you use retries:

playwright.config.ts
// playwright.config.ts
import { defineConfig } from "@playwright/test";

export default defineConfig({
  use: {
    // "off" (default) | "on" | "only-on-failure" | "on-first-failure"
    screenshot: { mode: "only-on-failure", fullPage: true },
    trace: "on-first-retry",
  },
});

Screenshots land in the output directory (test-results/ by default) and are linked from the HTML report. Pair them with traces: a trace records every action with DOM snapshots, which usually explains a failure faster than a single image.

pytest-playwright (Python)

The official pytest plugin has the same feature as command-line flags. --screenshot accepts on, off or only-on-failure, and --full-page-screenshot captures the whole page instead of the viewport:

terminal
pip install pytest-playwright
playwright install chromium

# Screenshot after every failing test, full page, into ./test-results
pytest --screenshot only-on-failure --full-page-screenshot
pytest.ini
# pytest.ini: make it the default for every run
[pytest]
addopts = --screenshot only-on-failure --full-page-screenshot

In Java and .NET, call page.screenshot() from your test framework's failure hook. For JUnit 5, an AfterTestExecutionCallback runs before @AfterEach closes the browser; our Selenium screenshot guide shows that pattern.

Compare screenshots in Playwright (visual testing)

toHaveScreenshot() is Playwright Test's visual regression assertion. It waits until two consecutive screenshots match (so the page has settled), then compares against a stored baseline using the pixelmatch library:

pricing.spec.ts
// tests/pricing.spec.ts
import { test, expect } from "@playwright/test";

test("pricing page looks right", async ({ page }) => {
  await page.goto("https://example.com/pricing");

  await expect(page).toHaveScreenshot("pricing.png", {
    fullPage: true,
    maxDiffPixels: 100,                         // tolerate tiny anti-aliasing noise
    mask: [page.locator(".price-updated-at")],  // ignore content that changes
  });

  await expect(page.locator("header")).toHaveScreenshot("header.png");
});
terminal
npx playwright test                      # first run writes the baselines (and reports them missing)
npx playwright test --update-snapshots   # accept intentional changes
  • First run: there's no baseline yet, so the test fails with "A snapshot doesn't exist at ... writing actual" and saves one. Commit the generated files.
  • Where baselines live: in a folder named after the test file (pricing.spec.ts-snapshots/), with the browser and OS in each file name. Name a snapshot with .webp to store it as WebP.
  • Different machines render differently. Fonts, GPU and OS change pixels, so generate and check baselines in the same environment, typically the same Docker image in CI.
  • Tolerance: maxDiffPixels or maxDiffPixelRatio allow a few changed pixels; threshold (default 0.2) is how different a pixel's color must be to count. In toHaveScreenshot(), animations default to disabled.
  • Snapshot vs screenshot: toMatchSnapshot() compares arbitrary text or binary data, and toMatchAriaSnapshot() compares the accessibility tree. toHaveScreenshot() is the image comparison.

Python, Java and .NET have no built-in screenshot assertion. There's no toHaveScreenshot() outside Playwright Test: the playwright-python source states that the Python API has no screenshot assertion, and playwright-java lists it as not ported. To compare screenshots in Python, capture them with page.screenshot() and diff the images yourself. A minimal version with Pillow:

compare.py
from PIL import Image, ImageChops   # pip install pillow

before = Image.open("baseline.png").convert("RGB")
after = Image.open("current.png").convert("RGB")

if before.size != after.size:
    raise AssertionError(f"size changed: {before.size} -> {after.size}")

diff = ImageChops.difference(before, after)
bbox = diff.getbbox()            # None when the images are identical
if bbox:
    diff.save("diff.png")
    raise AssertionError(f"pixels changed inside {bbox}")

That's an exact comparison. For real suites you'll want a tolerance and an ignore list, which is where third-party pytest plugins and hosted visual-testing services come in; evaluate them on their own docs.

Common Playwright screenshot problems

SymptomLikely causeFix
Blank or half-rendered imageCaptured before the app finished renderingWait for a selector that appears last, or wait_for_load_state('networkidle')
full_page captures one screenThe page scrolls inside a containerUnset fixed heights with add_style_tag, as shown above
Empty spaces where images should beLazy loading never triggeredScroll through the page before capturing
Text in boxes or wrong font in DockerFonts missing from the imageInstall font packages (for example fonts-noto-cjk, fonts-noto-color-emoji)
Blurry screenshotsDevice scale factor 1device_scale_factor=2 on the context
Visual tests pass locally, fail in CIDifferent OS, fonts or GPUCreate baselines in the CI environment (same Docker image)
Locator screenshot times outElement hidden, animating, or matches several nodesFix the locator; check visibility; use .first
Transparent background is whiteJPEG, or the page sets a background colorUse PNG/WebP and omit_background; remove the page background

Production screenshots without running browsers

Everything above is the right tool for tests. Production capture is a different job: link previews, social cards, archiving, monitoring, or screenshots of customer URLs. There you also need concurrency limits, retries, ad and cookie-banner blocking, caching and storage. If you'd rather not run that fleet, RenderKit's /v1/screenshot takes the same ideas as JSON and returns a hosted image URL:

PlaywrightRenderKit parameter
page.goto(url) / page.set_content(html)url / html (exactly one)
viewport={'width': ..., 'height': ...}viewport_width (default 1440), viewport_height (default 900)
device_scale_factordevice_scale, 1–3
full_page=Truefull_page: true
locator(sel).screenshot()selector (a 422 SELECTOR_NOT_FOUND error if nothing matches)
clipclip with integer x, y, width, height
type, qualityformat (png, jpeg, webp), quality 1–100
omit_backgroundomit_background
style / maskhide_selectors (hides elements rather than painting a box); inject_css on paid plans
devices['iPhone 13']mobile: true plus a phone viewport
Waitswait_until, wait_for_selector, delay; click and scroll_to before capture
No equivalentblock_ads, block_cookie_banners, block_chats, thumbnail_width
renderkit_screenshot.py
import os
from renderkit import RenderKit   # pip install renderkit-sdk

rk = RenderKit(os.environ["RENDERKIT_API_KEY"])

shot = rk.screenshot(
    url="https://example.com",
    full_page=True,
    format="webp",
    quality=80,
    device_scale=2,
    block_ads=True,
    block_cookie_banners=True,
    hide_selectors=[".chat-widget"],
)
print(shot["url"])   # hosted image on cdn.renderkit.tech, 1 credit
renderkit-screenshot.mjs
import { RenderKit } from "renderkit-sdk"; // npm install renderkit-sdk

const rk = new RenderKit(process.env.RENDERKIT_API_KEY);

// Element capture, like locator.screenshot()
const hero = await rk.screenshot({
  url: "https://example.com",
  selector: "#hero",
  omit_background: true,
});

// Thumbnail for a link preview
const thumb = await rk.screenshot({ url: "https://example.com", thumbnail_width: 400 });
console.log(hero.url, thumb.url);
  • Cost: 1 credit per screenshot. Repeat requests for the same render within the cache window cost 0, and failed renders are refunded. The free trial has 500 credits for 14 days; Hobby is $9/month for 5,000 screenshots. See pricing.
  • Region: screenshots render from France, so EU cookie-consent banners are common. That's what block_cookie_banners is for. Growth plans and above can pass country: "us" for US rendering.
  • Limits to know: the API only reaches public http(s) URLs, so a localhost dev server or a staging site behind a VPN won't work (send html instead). Pages that serve a bot wall are flagged with meta.blocked: true rather than silently returning the block page.
  • Keep Playwright for testing. The API doesn't replace toHaveScreenshot(), traces, or screenshots of your app mid-test. It replaces the screenshot service you'd otherwise build around Playwright. Parameters are in the screenshot API reference.

Common questions

Call page.screenshot(path='full.png', full_page=True). If images are missing, scroll through the page first so lazy loading triggers. If only one screen is captured, the page scrolls inside a container: add a style tag that sets height: auto and overflow: visible on html, body and the container before capturing.

Use a locator: page.locator('#pricing').screenshot(path='pricing.png') in Python, or await page.locator('#pricing').screenshot({ path: 'pricing.png' }) in JavaScript. Playwright waits for the element to be visible and stable and scrolls it into view first. Elements covering it stay visible in the capture.

In Playwright Test, set use: { screenshot: 'only-on-failure' } in playwright.config.ts (or { mode: 'only-on-failure', fullPage: true }). With pytest-playwright, run pytest --screenshot only-on-failure, optionally with --full-page-screenshot. Files go to the test-results folder. In Java and .NET, call page.screenshot() from your test framework's failure hook.

In Playwright Test use await expect(page).toHaveScreenshot('name.png'). The first run saves a baseline, later runs fail when pixels differ beyond maxDiffPixels or threshold, and npx playwright test --update-snapshots accepts changes. Python, Java and .NET have no built-in screenshot assertion, so capture with page.screenshot() and diff the images yourself, for example with Pillow.

A screenshot is an image, from page.screenshot() or the toHaveScreenshot() assertion. toMatchSnapshot() compares any text or binary value against a stored file, and toMatchAriaSnapshot() compares the page's accessibility tree. Use screenshots for visual layout and ARIA snapshots for structure; ARIA snapshots are far less sensitive to fonts and rendering.

Yes. Pass type='jpeg' or type='webp' with a quality from 0 to 100, or just use a .jpg or .webp file name, since the type is inferred from the path. WebP support arrived in Playwright 1.62, and quality 100 (its default) is lossless. omit_background does not work with JPEG.

Blank usually means it was taken before the app rendered: wait for a selector that appears last. Cut off with full_page=True usually means the page scrolls inside a container rather than the document. Missing images mean lazy loading never fired, so scroll through the page before capturing.

Run npx playwright test --update-snapshots. It overwrites the stored baselines with the current screenshots; review the changed image files in your diff before committing them.

Ship your first render in 60 seconds.

500 free credits to start. No card. Cancel by ignoring it.

Get your free key$npm i renderkit-sdk