Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
Use Playwright’s locator screenshot method: identify the element you want, then call locator.screenshot(). In JavaScript, the essential line is await page.locator('.header').screenshot({ path: 'header.png' });. The locator scopes the image to that matched element instead of capturing the entire page.
Capture one element in JavaScript
Minimal runnable example
The following script opens a page, locates an element with the header class, and writes a PNG file. Replace the URL and selector with values from your page.
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');
const header = page.locator('.header');
await header.screenshot({ path: 'header.png' });
await browser.close();
})();
Install Playwright in the project using your normal package manager before running the script. The browser process must be closed even when you add more capture logic; in production code, use a try/finally block so a failed navigation does not leave browser processes running.
What the locator controls
The locator is the boundary of the image. A CSS locator such as .header captures the element matching that selector. You can use a more specific CSS path, a test identifier, or a role-oriented locator when that better represents the interface contract. Choose a locator that identifies the intended component rather than a styling class that may change during a redesign.
#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 card = page.getByRole('article').first();
await card.screenshot({ path: 'first-card.png' });
If a selector can match several nodes, make the target explicit with a filtering condition, first(), or nth(index). This prevents a capture job from silently targeting the wrong repeated component and makes visual tests easier to review.
Save a file or keep the image in memory
Passing path writes the screenshot to disk. Without a path, Playwright returns screenshot data, which is useful when the next step is an upload, an image comparison, or another in-memory transformation.
const imageBytes = await page.locator('.header').screenshot();
// imageBytes is the returned screenshot data; send it to your own pipeline.
Use a deterministic filename when creating an archive, and include the page state or test case in that name. For a service that streams images elsewhere, omit path and pass the returned bytes directly to the destination instead of creating temporary files.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Screenshot options that matter
The screenshot API documents options for output format, quality, scaling, clipping, masking, caret handling, styles, and animation behavior. Exact option names can differ between language bindings or Playwright releases, so verify the reference for the version installed in your project.
| Option or concern | Use it when | Important detail |
|---|---|---|
path |
You need a file artifact | With no path, the method returns screenshot data instead. |
type |
You need PNG, JPEG, or WebP output | Choose the format that matches your storage or delivery pipeline. |
quality |
You use JPEG or WebP and need a size/quality trade-off | Quality does not apply to PNG; the documented default JPEG quality is 80. |
scale |
You need predictable pixel dimensions or high-DPI output | css produces one image pixel per CSS pixel; device uses device pixels and can produce a larger image on high-DPI devices. |
| masking | Dynamic values such as timestamps or account names would create noise | Mask the changing regions so visual comparisons focus on layout and styling. |
animations: 'disabled' |
You need repeatable captures | Finite animations complete immediately and infinite animations are treated as disabled for the capture. This changes the animation state in the image. |
| style and caret controls | Injected presentation rules or text-caret behavior affect the result | Check the installed binding’s API reference for the accepted syntax. |
For example, a WebP capture with CSS-pixel scaling and disabled animations can be written as:
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
await page.locator('.header').screenshot({
path: 'header.webp',
type: 'webp',
quality: 80,
scale: 'css',
animations: 'disabled'
});
Element capture versus a full-page screenshot
Use locator.screenshot() when the deliverable is one component: a navigation bar, product card, chart, invoice panel, or modal. It keeps unrelated page content out of the image and avoids having to calculate a clip rectangle yourself.
Use the page method for a page-wide image:
await page.screenshot({
path: 'whole-page.png',
fullPage: true
});
fullPage: true captures the full scrollable page. A page screenshot can also be returned as data for post-processing rather than written directly to a file. Do not substitute a full-page capture when a test or downstream consumer expects the dimensions of a single element.
Python: synchronous and asynchronous forms
Synchronous Python
The Python locator API follows the same pattern: navigate, create a locator, and call its screenshot method with a path.
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page(viewport={"width": 1440, "height": 900})
page.goto("https://example.com")
page.locator(".header").screenshot(path="header.png")
browser.close()
Asynchronous Python
Use the asynchronous binding when the rest of your application already uses asyncio.
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(viewport={"width": 1440, "height": 900})
await page.goto("https://example.com")
await page.locator(".header").screenshot(path="header.png")
await browser.close()
asyncio.run(main())
Python also lets you omit path when you need the returned screenshot data. Keep the option spelling appropriate to the synchronous or asynchronous reference for the version you installed.
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.
Make captures repeatable
Wait for the state you intend to document
A screenshot is only as meaningful as the page state at capture time. Navigate to the correct URL, perform required interactions, and identify the target with a locator that reflects the final UI. If the element is rendered after an interaction, perform that interaction before calling screenshot.
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Control animation and changing content
Disable animations when motion would make two otherwise identical captures differ. Mask clocks, rotating promotions, personalized names, and other values that are expected to change. If those values are the subject of the test, leave them visible and control the test data instead of masking them.
Choose a scale deliberately
css scale is generally easier to compare because image dimensions follow CSS pixels. device scale is useful when you need the extra pixels of a high-DPI device, but it increases image dimensions and often file size. Use the same scale across a visual-regression baseline and its later comparisons.
Keep the viewport and browser context stable
Set the viewport explicitly when dimensions matter. A different viewport can trigger a responsive breakpoint and change the element’s size or layout. Keep browser context settings consistent across baseline and comparison runs.
Common failures and fixes
The image is empty or the target is not visible
- Confirm that the URL is the page you expect and that the selector matches the rendered element.
- Capture after the interaction or page state that creates the component.
- Check whether a responsive viewport hides or replaces the element.
The wrong repeated element is captured
Make the locator narrower by scoping it to a parent, filtering by text or another attribute, or selecting an explicit index. A generic class used by several cards is not enough to identify one card reliably.
Do these 3 things before closing this tab:
1Scan for outdated or missing drivers - takes under a minute2Repair Windows errors before they cause bigger problems3Fix the driver behind crashes, sound loss and screen glitchesRank #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
The capture differs on every run
- Use a fixed viewport and stable test data.
- Disable animations when motion is not part of the requirement.
- Mask timestamps, rotating content, and other intentionally variable regions.
- Use a consistent
scaleand image type.
The output file is unexpectedly large
Use css scale instead of device when high-DPI pixels are unnecessary. For JPEG or WebP, set an appropriate quality value; PNG quality settings do not reduce its size in the same way.
An option is rejected by the binding
The shared API documentation includes aliases and language-specific differences. Check the locator screenshot reference for your installed Playwright version and language rather than copying an option name from another binding. The locator screenshot method is documented as available from Playwright v1.14 onward.
The browser process remains after an error
Close the browser in a cleanup path. In JavaScript, place capture work inside try/finally; in Python, use the context managers shown above and still close explicitly if you create a browser outside them.
Performance, reliability, and cost considerations
An element screenshot avoids the pixels and layout work of a full-page image, which is useful when a test suite captures many small components. The largest factors in runtime are page navigation, application rendering, and any waits or interactions before the capture. Reuse a browser process for a batch of captures, while creating isolated contexts when state must not leak between tests.
File format affects storage and transfer. PNG preserves lossless detail, whereas JPEG and WebP can reduce payload size when their quality setting is acceptable for your comparison or delivery use case. Keep the format and quality constant for visual baselines.
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.
Playwright itself does not charge per screenshot; your costs come from the machines, browser runtime, storage, and any external capture service you add. Failed navigations and missing selectors should be surfaced as job failures, not accepted as valid image artifacts. Record the URL, selector, viewport, format, scale, and relevant option values alongside each image so a later mismatch can be reproduced.
Or skip the browser setup
ScreenshotNeo provides a website screenshot API and MCP server. It can capture a single element by CSS selector as well as full pages, and it supports formats including PNG, JPEG, WebP, and PDF. The API can remove cookie-consent banners, newsletter popups, and chat widgets before capture; each of those cleanup steps can be turned off. Use the selector option described in the ScreenshotNeo documentation when the target is one element.
A basic one-call capture looks like this:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
The same request in Python:
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)
And in Node.js:
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
ScreenshotNeo reports whether a response was a clean shot, a bot check or CAPTCHA, a blank page, a timeout, a failed load, or a cache hit through response headers. Only clean shots are billed; those other outcomes and cache hits cost nothing. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf tools to Claude, Cursor, and other MCP clients, so an AI agent can request captures without you wiring a browser into the agent.
PC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchThe Free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 screenshots; every feature is available on every plan, and yearly billing provides two months free. Create a free ScreenshotNeo account to try it without a card.
FAQ
Which Playwright release introduced locator screenshots?
The Locator API reference marks locator.screenshot as added in Playwright v1.14. Confirm the method and option set against the version installed in your project because the live API can change.
Do option names work identically in JavaScript and Python?
Not necessarily. The shared API reference documents aliases and binding-specific spellings, so check the language-specific reference before moving a configuration between JavaScript, Python, or another Playwright binding.
Frequently Asked Questions
Which Playwright release introduced locator screenshots?
The Locator API reference marks locator.screenshot as added in Playwright v1.14. Confirm the method and option set against the version installed in your project because the live API can change.
The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Do option names work identically in JavaScript and Python?
Not necessarily. The shared API reference documents aliases and binding-specific spellings, so check the language-specific reference before moving a configuration between JavaScript, Python, or another Playwright binding.
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.

