Use locator.screenshot() when the area is a DOM element, and use page.screenshot({ clip }) when you need an arbitrary rectangle. The locator approach follows the element as the layout changes; a clip uses fixed coordinates. Both methods can save an image to disk or return image bytes for processing.
Choose the right Playwright screenshot method
| Goal | API | Best when | Main limitation |
|---|---|---|---|
| Capture one component or element | locator.screenshot() |
The desired region maps to a stable DOM element | The target must remain attached to the document |
| Capture a coordinate rectangle | page.screenshot({ clip }) |
No single element represents the region | Coordinates can become wrong when layout or viewport changes |
| Capture the entire document | page.screenshot({ fullPage: true }) |
You need all scrollable page content | It is not a partial capture |
| Process the image in memory | await page.screenshot() |
Visual tests, uploads, hashing or image analysis | You must handle the returned bytes yourself |
Prerequisites and a minimal setup
Install Playwright and its browser binaries in your project:
npm install -D playwright
npx playwright install
The examples below use JavaScript with the Playwright library. They assume a page has loaded before the capture call. In a test project, put the same calls inside a Playwright test or fixture.
Capture one element with locator.screenshot()
For a DOM-backed region, create a locator and call its screenshot method:
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →#1 Best Overall
- CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
- INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
- THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
- WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
- A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents
const { chromium } = require('playwright');
(async () => {
const browser = await chromium.launch();
const page = await browser.newPage({ viewport: { width: 1440, height: 900 } });
await page.goto('https://example.com', { waitUntil: 'networkidle' });
await page.locator('.header').screenshot({ path: 'header.png' });
await browser.close();
})();
The locator screenshot waits for actionability, scrolls the element into view and captures the element’s region. Prefer a semantic locator when possible:
await page.getByRole('banner').screenshot({ path: 'banner.png' });
await page.locator('[data-testid="pricing-card"]').screenshot({ path: 'pricing-card.webp', type: 'webp' });
Make the locator unambiguous
A locator that resolves to multiple elements is not a reliable capture target. Narrow it with a role, test id, text, class, or nth() only when the order is intentional:
const card = page.getByRole('article', { name: 'Pro plan' });
await card.screenshot({ path: 'pro-plan.png' });
If the element is created asynchronously, wait for a meaningful state before taking the shot:
const chart = page.locator('#sales-chart');
await chart.waitFor({ state: 'visible' });
await page.waitForTimeout(300); // allow a client-side render to settle
await chart.screenshot({ path: 'sales-chart.png' });
Element screenshots and scrollable containers
An element screenshot represents the element’s rendered box. For a scrollable panel, it normally shows the content currently visible inside that panel, not every item hidden behind its internal scrollbar. Scroll the container deliberately, or target a child whose rendered height contains the content you need:
Free tools Windows power users keep installed
One-click scans. No signup required.
const panel = page.locator('.results-panel');
await panel.evaluate(el => { el.scrollTop = 0; });
await panel.screenshot({ path: 'panel-top.png' });
await panel.evaluate(el => { el.scrollTop = el.scrollHeight; });
await panel.screenshot({ path: 'panel-bottom.png' });
Capture an arbitrary rectangle with clip
Use page coordinates when the region is defined by a fixed rectangle rather than a DOM node:
await page.screenshot({
path: 'region.png',
clip: { x: 0, y: 120, width: 800, height: 400 }
});
x and y are the rectangle’s top-left coordinates. width and height define its size. Coordinates are relative to the page’s viewport, so changing the viewport, responsive breakpoint, browser UI assumptions, or page layout can move the content away from the intended rectangle.
Rank #2
- CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
- 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
- SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
- INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
- THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
Calculate a rectangle from an element
If you need clip processing but want the rectangle to follow layout, read the element’s bounding box first:
const box = await page.locator('.hero').boundingBox();
if (!box) throw new Error('Hero is not visible or has no box');
await page.screenshot({
path: 'hero-clip.png',
clip: { x: box.x, y: box.y, width: box.width, height: box.height }
});
This combines layout-aware positioning with the page screenshot API. Recheck the box immediately before capture if animations or reflows can change its dimensions.
Recommended Free Tools
Control output format, scale and destination
PNG, JPEG and WebP
PNG is lossless and is usually best for text, UI comparison and transparency. JPEG is smaller for photographic content but loses quality. WebP can reduce size while retaining good quality. Set the format through the file extension or the type option:
await page.locator('.map').screenshot({ path: 'map.jpg', type: 'jpeg', quality: 85 });
await page.screenshot({ path: 'region.webp', type: 'webp', quality: 80 });
Quality applies to JPEG and WebP; it has no useful effect on PNG.
Device-pixel scale and retina output
The browser context’s device scale factor controls how CSS pixels become image pixels. Use a larger value for high-density visual artifacts:
const context = await browser.newContext({
viewport: { width: 1280, height: 800 },
deviceScaleFactor: 2
});
Keep the viewport and scale factor constant in visual regression tests. Otherwise, image dimensions and antialiasing can differ even when the page is unchanged.
Rank #3
- Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
- Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
- Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
- In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
- Ultra-thin bezels: Maximize your viewing experience with thin bezels.
Return bytes instead of writing a file
const imageBytes = await page.locator('.invoice').screenshot();
await require('fs').promises.writeFile('invoice.png', imageBytes);
The returned value is a byte buffer. You can upload it, compare it with a baseline, or pass it to an image-processing library without creating a temporary file.
Stabilize dynamic pages before capturing
- Wait for the target: use
locator.waitFor({ state: 'visible' })or a page assertion. - Wait for data: wait for a specific response, loading indicator to disappear, or text to appear instead of relying only on a fixed delay.
- Disable motion: inject a stylesheet that turns off transitions and animations when repeatability matters.
- Mask volatile regions: mask timestamps, rotating ads, cursors or user-specific data when your Playwright version supports screenshot masking.
- Freeze the environment: set a known viewport, locale, timezone, color scheme and device scale factor.
await page.addStyleTag({ content: `
*, *::before, *::after {
animation: none !important;
transition: none !important;
caret-color: transparent !important;
}
` });
For a dark-mode capture, create the context with colorScheme: 'dark' before navigating. For lazy-loaded content, scroll the relevant area into view and wait for the images you need before capturing.
Common failures and fixes
“Locator resolved to multiple elements”
Cause: the selector matches more than one node. Fix: use a role and accessible name, a test id, a parent-child locator, or an intentional nth() selection.
“Element is not attached to the DOM”
Cause: a framework replaced the node between lookup and capture. Fix: locate again after rendering settles, wait for the stable state, and avoid storing an element handle across a rerender. Locators are generally safer because they resolve at action time.
The screenshot is blank or the wrong region
Cause: the page has not finished loading, the clip is outside the viewport, or the coordinates were measured in a different viewport. Fix: set the viewport explicitly, wait for the target, use locator.screenshot() where possible, and log the element’s bounding box.
A panel is cut off
Cause: the panel has an internal scrollbar or a fixed height. Fix: capture the visible state, scroll and capture multiple regions, or temporarily adjust the panel’s CSS if your use case permits it. A normal element screenshot does not automatically create a stitched image of an internal scroll area.
Rank #4
- CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
- SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
- MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
- KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
- INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient
Fonts or images differ in CI
Cause: missing fonts, different browser binaries, network timing or device scale. Fix: install the same Playwright browsers in CI, wait for fonts and images, use deterministic test data, and pin viewport and context settings.
Animations make comparisons flaky
Cause: the capture occurs at a different animation frame. Fix: disable animations with injected CSS, wait for a known state, or use screenshot masking for intentionally dynamic content.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →When to use full-page capture instead
fullPage: true captures the page’s full scrollable document, which is useful for long articles and regression artifacts. It is not a substitute for a component screenshot: it may include unrelated navigation, cookie notices and ads, and it produces a larger file. Use a locator for a component, a clip for a rectangle, and full-page mode only when the document itself is the subject.
Or skip the browser setup
ScreenshotNeo provides a website screenshot API and MCP server. A single GET request returns a PNG, JPEG, WebP or PDF, without installing Playwright or managing a browser:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
See the ScreenshotNeo documentation for all parameters. Equivalent Python and Node.js calls are:
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
It can capture a CSS-selected element, full pages, dark mode, custom viewport and device presets, retina scale, PDFs, HTML/CSS, custom JavaScript, clicks, waits, hidden selectors, blocked ads or trackers, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, chosen cache TTLs, signed image links, asynchronous webhooks, bulk requests for up to 100 URLs and usage data. Cookie banners, newsletter popups and chat widgets are removed before capture; bot checks, blank pages, timeouts, failed loads and cache hits are not billed, and response headers identify the page verdict and billing result. Its MCP server exposes take_screenshot, get_page_info and capture_pdf to Claude, Cursor and other MCP clients. The Free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots. Sign up free for ScreenshotNeo.
FAQ
Can I screenshot an element that is below the fold?
Yes. A locator screenshot scrolls the target into view before capture. For a clip, scroll first and calculate coordinates in the resulting viewport.
Best Value
- 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
- 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
- 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.
Can Playwright capture only part of an iframe?
Locate the frame with page.frameLocator(), target an element inside it, and call that locator’s screenshot method. Cross-origin restrictions can still affect what page scripts can inspect.
How do I name screenshots for parallel tests?
Include the test name, browser or project and a unique case identifier in the path. This prevents workers from overwriting each other’s artifacts.
Frequently Asked Questions
Can I screenshot an element that is below the fold?
Yes. A locator screenshot scrolls the target into view before capture. For a clip, scroll first and calculate coordinates in the resulting viewport.
Can Playwright capture only part of an iframe?
Locate the frame with page.frameLocator(), target an element inside it, and call that locator’s screenshot method. Cross-origin restrictions can still affect what page scripts can inspect.
How do I name screenshots for parallel tests?
Include the test name, browser or project and a unique case identifier in the path. This prevents workers from overwriting each other’s artifacts.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

