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:
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:
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 (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:
// 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
// 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)
// 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
| Python | JavaScript / TypeScript | Default | What it does |
|---|---|---|---|
path | path | none | Where to save. The image type is inferred from the extension. |
full_page | fullPage | False | Capture the full scrollable page instead of the viewport. |
clip | clip | none | Capture only a rectangle: x, y, width, height. |
type | type | png | png, jpeg or webp (WebP since Playwright 1.62). |
quality | quality | JPEG 80, WebP 100 | 0–100. Not for PNG. WebP at 100 is lossless. |
omit_background | omitBackground | False | Drop the default white background for transparency. Not for JPEG. |
animations | animations | allow | disabled fast-forwards finite CSS animations and transitions and cancels infinite ones. |
caret | caret | hide | Hide the blinking text cursor, or keep it with initial. |
mask | mask | none | List of locators to paint over with a solid box. |
mask_color | maskColor | #FF00FF | Color of the mask boxes (since 1.35). |
style | style | none | CSS applied only while capturing; it pierces shadow DOM and iframes (since 1.41). |
scale | scale | device | css 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:
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:
# 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:
# 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 sametype,quality,mask,style,animationsandomit_backgroundoptions;full_pageandclipare 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
.firstor.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
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 PNGPNG 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:
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.maskpaints 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.styleinjects 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 withwait_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:
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
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:
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: make it the default for every run
[pytest]
addopts = --screenshot only-on-failure --full-page-screenshotIn 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:
// 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");
});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.webpto 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:
maxDiffPixelsormaxDiffPixelRatioallow a few changed pixels;threshold(default 0.2) is how different a pixel's color must be to count. IntoHaveScreenshot(), animations default to disabled. - Snapshot vs screenshot:
toMatchSnapshot()compares arbitrary text or binary data, andtoMatchAriaSnapshot()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:
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
| Symptom | Likely cause | Fix |
|---|---|---|
| Blank or half-rendered image | Captured before the app finished rendering | Wait for a selector that appears last, or wait_for_load_state('networkidle') |
full_page captures one screen | The page scrolls inside a container | Unset fixed heights with add_style_tag, as shown above |
| Empty spaces where images should be | Lazy loading never triggered | Scroll through the page before capturing |
| Text in boxes or wrong font in Docker | Fonts missing from the image | Install font packages (for example fonts-noto-cjk, fonts-noto-color-emoji) |
| Blurry screenshots | Device scale factor 1 | device_scale_factor=2 on the context |
| Visual tests pass locally, fail in CI | Different OS, fonts or GPU | Create baselines in the CI environment (same Docker image) |
| Locator screenshot times out | Element hidden, animating, or matches several nodes | Fix the locator; check visibility; use .first |
| Transparent background is white | JPEG, or the page sets a background color | Use 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:
| Playwright | RenderKit 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_factor | device_scale, 1–3 |
full_page=True | full_page: true |
locator(sel).screenshot() | selector (a 422 SELECTOR_NOT_FOUND error if nothing matches) |
clip | clip with integer x, y, width, height |
type, quality | format (png, jpeg, webp), quality 1–100 |
omit_background | omit_background |
style / mask | hide_selectors (hides elements rather than painting a box); inject_css on paid plans |
devices['iPhone 13'] | mobile: true plus a phone viewport |
| Waits | wait_until, wait_for_selector, delay; click and scroll_to before capture |
| No equivalent | block_ads, block_cookie_banners, block_chats, thumbnail_width |
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 creditimport { 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_bannersis for. Growth plans and above can passcountry: "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 (sendhtmlinstead). Pages that serve a bot wall are flagged withmeta.blocked: truerather 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.