Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use a locator’s screenshot() method to capture exactly one matched element. In JavaScript, the smallest working example is await page.locator('.header').screenshot({ path: 'header.png' });. In Python, use page.locator('.header').screenshot(path='header.png'). A supplied path writes the image; without one, Playwright returns screenshot data that you can process in memory.

Capture one element in JavaScript

Start a browser, open the page, create a locator for the element, and call screenshot() on that locator. This complete script saves the matched element as a PNG:

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();
})();

Replace .header with a selector that identifies the element you intend to capture. The locator is resolved when the screenshot is taken, so navigation and waiting should happen before the call.

Use a role or accessible name when it is more stable

A CSS class can change when a design is refactored. A role-based locator expresses what the element is rather than how it is styled:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
await page.getByRole('button', { name: 'Subscribe' }).screenshot({
  path: 'subscribe-button.png'
});

Choose a locator that describes the target unambiguously. If a selector can match several elements, refine it with a role, accessible name, text, or another condition so the capture has one intended target.

Python equivalents

Synchronous Python API

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", wait_until="networkidle")
    page.locator(".header").screenshot(path="header.png")
    browser.close()

Asynchronous Python API

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", wait_until="networkidle")
        await page.locator(".header").screenshot(path="header.png")
        await browser.close()

asyncio.run(main())

The synchronous and asynchronous forms call the same locator operation. Use the style that matches the rest of your test or automation code.

Element screenshots versus page screenshots

locator.screenshot() limits the capture to the element matched by the locator. It is the right method for a card, header, chart, button, or other component. A page screenshot has a different scope:

await page.screenshot({ path: 'full-page.png', fullPage: true });

fullPage: true captures the page’s full scrollable area rather than one element. Use it for visual regression of an entire document. Do not switch to a page screenshot merely because the target element is below the fold; Playwright can scroll an element into view as part of the locator capture.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose the output form

Goal Method Result
Save an element directly await locator.screenshot({ path: 'element.png' }) Image written to the specified path
Keep the image in memory const buffer = await locator.screenshot() Screenshot bytes for upload, comparison, or transformation
Save a whole page await page.screenshot({ path: 'page.png', fullPage: true }) Full scrollable-page image

In Python, omit path to receive screenshot data instead of writing a file. This is useful when a test compares bytes, sends the result to object storage, or attaches it to a report without creating a temporary file.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Useful screenshot options

The screenshot API exposes options for file format, dimensions, clipping, masking, styling, and animation. Exact option names can vary by language binding, so check the API reference for the Playwright version installed in your project.

Format and quality

Use a filename extension or the documented type option to select PNG, JPEG, or WebP where supported by your binding. The quality option applies to JPEG and WebP, not PNG; the documented JPEG default is 80. Quality reduces file size at the cost of compression artifacts, so PNG is normally safer for text and pixel-level comparisons.

await page.locator('.chart').screenshot({
  path: 'chart.webp',
  type: 'webp',
  quality: 85
});

CSS pixels or device pixels

The documented scale choices are css and device. css produces one image pixel per CSS pixel. device uses device pixels and can produce a larger image on a high-DPI context. Use css for stable visual comparisons across machines; use device when you need the rendered density of the emulated device.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
await page.locator('.hero').screenshot({
  path: 'hero.png',
  scale: 'css'
});

Mask dynamic or private content

Masking lets you cover regions that change between runs, such as timestamps, avatars, or account identifiers. Supply the masking configuration supported by your installed binding and keep the mask limited to the unstable region. Masking is preferable to hiding content when the layout itself must remain part of the comparison.

Control animation and caret rendering

For repeatable output, consider the locator screenshot option animations: 'disabled'. The API documents different treatment for finite and infinite animations when they are disabled, so use this only when a static frame is more useful than the natural animation state. Caret handling is another documented option; disable a text caret when it would introduce a blinking pixel into a comparison.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Clip, style, and full-page flags

The API reference documents clipping and style controls in addition to the locator’s natural element bounds. Use clipping when you need a sub-region, a style option when capture-only CSS is required, and fullPage only when the intended scope is the complete scrollable document. Confirm which aliases your language binding accepts before copying an option from a different language’s example.

Make the capture deterministic

Wait for the page state you need

Navigation completion alone does not guarantee that the target has finished rendering. Wait for a meaningful selector, a known application state, or a deliberate delay when the page is driven by client-side code. A network-idle wait can help on pages that load assets after navigation, but it is not a universal signal that every animation or data refresh is complete.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
await page.goto('https://example.com/dashboard');
await page.locator('.dashboard-card').waitFor();
await page.locator('.dashboard-card').screenshot({ path: 'dashboard-card.png' });

Fix layout differences before taking the shot

  • Set an explicit viewport so line wrapping and responsive breakpoints are consistent.
  • Set the same color scheme, device scale, locale, timezone, and other context settings for every run when those values affect rendering.
  • Wait for fonts and application data that visibly change the target.
  • Disable or mask animation only when the test’s purpose requires a stable frame.
  • Use a stable selector rather than a generated class name.

Capture a component that is initially hidden

An element that is not rendered or is hidden behind an interaction cannot produce the intended visual. Perform the same action a user would—such as opening a menu or expanding an accordion—then wait for the target and capture it:

await page.getByRole('button', { name: 'Details' }).click();
const panel = page.locator('.details-panel');
await panel.waitFor();
await panel.screenshot({ path: 'details-panel.png' });

Common failures and fixes

“Locator” does not match an element

The selector may be wrong, the page may not have finished navigating, or the element may be created only after an action. Inspect the rendered DOM, verify the URL, wait for the target selector, and prefer a role-based locator when the markup is stable but classes are not.

The screenshot times out

A timeout usually means Playwright is still waiting for the locator to resolve, become actionable, or reach a capturable state. Check for a typo, a frame boundary, a blocked navigation, or an element that remains hidden. Increase the timeout only after correcting the condition that prevents the element from appearing.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

The image contains a transient animation

Use animations: 'disabled' when a static frame is the desired test artifact, or wait for a known animation endpoint. If the animation itself is what you are testing, leave it enabled and define when the capture should occur.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The image is unexpectedly large or blurry

Check the viewport and scale. Device-pixel scale can multiply dimensions on high-DPI contexts. For JPEG or WebP, check quality; PNG ignores that setting. Also verify that you did not request a full-page capture when you meant to capture one locator.

Only part of a component appears

Look for clipping, overflow, transforms, or a component whose content expands after the initial render. Wait for the final layout, remove an unintended clip region, and capture the locator that owns the complete component rather than an inner wrapper with constrained dimensions.

The target is inside an iframe

A page locator cannot directly address content in a separate frame. First obtain the appropriate frame, then create the locator within that frame and call its screenshot method. Keep the frame selection tied to a stable URL, name, or frame locator rather than an index that can change.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Version and language considerations

The Locator screenshot method was added in Playwright v1.14. Projects using an older installation should upgrade or use the screenshot capability available in that version. The API reference is shared across several language bindings and includes alias names; an option shown in a general parameter reference may not have identical spelling or availability in JavaScript, Python, or another binding. Pin and inspect the Playwright version used by your CI environment, then verify option names against that version’s API reference.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Or skip the browser setup

If you need a website image rather than a locally scripted browser workflow, ScreenshotNeo provides a website screenshot API and MCP server. Its capture options include selecting one element by CSS selector, full-page shots, custom CSS and JavaScript, device and viewport settings, lazy-image loading, waits, masking, request blocking, cookies, headers, geolocation, PDF output, caching, asynchronous jobs, bulk capture, and signed links. The API also accepts the parameter names used by other screenshot APIs, which can simplify a migration.

Call the API with one GET request (the URL below uses Stripe as the target):

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 the element selector and other capture parameters. Before the capture, it can accept cookie or consent banners and remove more than 60 known consent platforms, newsletter popups, and chat widgets, with each step configurable. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing; response headers identify the page verdict and whether the request was billed. An MCP server exposes take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients.

ScreenshotNeo includes 1,000 shots per month on the free plan with no card required. Paid plans start at $5 for 3,000 shots; every feature is available on every plan, and yearly billing provides two months free. Create a free ScreenshotNeo account to start.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Practical checklist

  1. Choose a locator that identifies the intended element exactly.
  2. Navigate and wait for the target’s final rendered state.
  3. Set a deterministic viewport and context.
  4. Call locator.screenshot() with a path or keep the returned bytes in memory.
  5. Select format, quality, scale, masking, clipping, and animation behavior deliberately.
  6. Use page.screenshot({ fullPage: true }) only when the requirement is a full page.
  7. Verify option spelling against the Playwright version and language binding installed in your project.

Frequently Asked Questions

Which Playwright method captures just one component?

Call screenshot() on the locator for that component, not on the page object.

Can I send an element screenshot directly to another service?

Yes. Omit the path and use the returned screenshot bytes as the request body or attachment in your own code.

When should I use a full-page screenshot instead?

Use page.screenshot({ fullPage: true }) when the required artifact is the complete scrollable document rather than a single matched element.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.