DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
browser automation

How to Take Screenshots with Playwright (Viewport, Full Page, Elements, and Tests)

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

Use await page.screenshot({ path: 'screenshot.png' }) for the current viewport, add fullPage: true for the entire scrollable document, or call screenshot() on a locator to capture one element. Playwright can save PNG, JPEG, or WebP files, return image bytes for further processing, and produce repeatable visual-test artifacts when you control animations, masks, and page readiness.

This guide covers setup, reliable capture code, image options, Playwright Test integration, troubleshooting, and a hosted alternative when you do not want to maintain browser automation.

Set up Playwright before capturing

Install Playwright in the project that will run the capture. For a Node.js project, install the library and browser binaries:

npm install -D playwright
npx playwright install

If you use the Playwright test runner instead, create a test project with npm init playwright@latest. The examples below assume an async function and a Chromium, Firefox, or WebKit browser selected through Playwright.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB
  • 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

Minimal runnable script

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: 'domcontentloaded' });
  await page.screenshot({ path: 'screenshot.png' });
  await browser.close();
})();

page.goto() only tells you that the selected navigation condition occurred. Single-page applications, images, ads, and API-driven components may still be changing, so wait for an application-specific selector or state before taking the image.

Capture the viewport, full page, or a defined rectangle

Current viewport

await page.screenshot({ path: 'viewport.png' });

This captures what is visible in the viewport. The default is not the complete document. The Page API documents fullPage as false by default.

Entire scrollable page

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

Playwright describes a full-page image as the full scrollable page “as if you had a very tall screen and the page could fit it entirely.” This is useful for design review and documentation, but very long pages can create large images and increase memory use.

Explicit clip rectangle

await page.screenshot({
  path: 'hero-region.png',
  clip: { x: 0, y: 0, width: 1200, height: 700 }
});

clip uses page coordinates and requires a rectangle with x, y, width, and height. Choose clipping when you need a fixed region rather than the whole document.

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

Capture one element with a locator

Use a locator rather than the older elementHandle.screenshot() approach:

await page.locator('.header').screenshot({ path: 'header.png' });

The locator method waits for actionability checks and scrolls the matched element into view. It captures the visible state of a scrollable element; content hidden outside that element’s scrollport is not automatically expanded. The Locator API defines this as a screenshot clipped to the matched element.

Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB
  • 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

Use a stable selector

const card = page.getByTestId('pricing-card');
await card.waitFor({ state: 'visible' });
await card.screenshot({ path: 'pricing-card.webp', type: 'webp', quality: 85 });

Prefer test IDs, roles, or other selectors that are part of your application contract. A broad CSS selector can match multiple nodes or change when the layout changes.

Save to disk or keep the image in memory

Write a file

Providing path writes the result to disk. The extension can select the output type; you can also set type explicitly.

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

Return a buffer

const buffer = await page.screenshot();
console.log(buffer.toString('base64'));

Without path, Playwright returns a buffer. You can upload it, pass it to an image-diff library, attach it to a report, or encode it as base64 without creating a temporary file. The official screenshots guide demonstrates this pattern.

Choose format, quality, and pixel scale

  • PNG: the default and suitable for lossless UI captures and transparency.
  • JPEG: smaller files for photographs; quality applies and defaults to 80.
  • WebP: supports quality control; the documented default quality is 100 (lossless).
await page.screenshot({
  path: 'screen.jpg',
  type: 'jpeg',
  quality: 80,
  scale: 'css'
});

scale: 'css' creates one image pixel per CSS pixel. scale: 'device' uses device pixels and can make high-DPI output substantially larger; direct page screenshots use device scale by default. Set the scale deliberately when comparing images from different machines.

Transparent backgrounds

await page.screenshot({
  path: 'logo.png',
  omitBackground: true
});

omitBackground: true removes Playwright’s default white background for formats that support transparency. It has no effect for JPEG.

Make captures repeatable and safe

Disable motion

await page.screenshot({
  path: 'stable.png',
  animations: 'disabled'
});

With animations disabled, finite animations are fast-forwarded and infinite animations are canceled for the capture, then resumed. This reduces differences caused by transitions and carousels.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • 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.

Mask dynamic or private regions

await page.screenshot({
  path: 'masked.png',
  mask: [page.locator('[data-testid="account-name"]'), page.locator('.live-counter')],
  maskColor: '#808080'
});

Masks cover locator bounding boxes. Use them for timestamps, randomized content, personal data, and counters that should not participate in a visual comparison.

Inject a stylesheet

await page.screenshot({
  path: 'no-chat.png',
  style: '.chat-widget, .cookie-banner { display: none !important; }'
});

Styles are useful when a third-party widget obscures the page or when you need a deterministic test fixture. Do not hide an element if its visibility is the behavior under test.

Wait for the state you actually need

await page.goto('https://example.com/dashboard');
await page.getByRole('heading', { name: 'Dashboard' }).waitFor();
await page.waitForLoadState('networkidle');
await page.screenshot({ path: 'dashboard.png' });

networkidle can remain unreachable on applications with polling or analytics. In those cases, prefer a visible heading, a loaded table row, or a response you control. A fixed timeout is a last resort because it can be either too short or unnecessarily slow.

Use screenshots in Playwright Test

Playwright Test can save artifacts automatically. This is separate from calling page.screenshot() yourself. In playwright.config.ts:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import { defineConfig } from '@playwright/test';

export default defineConfig({
  use: {
    screenshot: 'only-on-failure'
  }
});

Documented modes are off, on, only-on-failure, and on-first-failure; the default is off. See TestOptions for configuration details.

Visual regression assertions

import { test, expect } from '@playwright/test';

test('home page has the expected design', async ({ page }) => {
  await page.goto('https://example.com');
  await expect(page).toHaveScreenshot('home.png');
});

expect(page).toHaveScreenshot() and expect(locator).toHaveScreenshot() wait until two consecutive screenshots are identical before comparing them with the stored expectation. These assertions require the Playwright test runner. Their page, locator, and assertion references are collected in the PageAssertions and LocatorAssertions documentation.

Rank #4
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor
  • 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

Common failures and fixes

The image is only the visible screen

Add fullPage: true. If you need a specific region, use clip instead; those options solve different problems.

An element screenshot is cut off

A locator screenshot captures the currently visible portion of a scrollable container. Capture the container’s contents by scrolling it yourself, redesigning the test fixture, or taking several clips; fullPage is a page-level option and does not turn an element into an infinitely tall image.

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

The selector matches nothing

Check the selector in the browser inspector, wait for the element’s state, and use a role or test ID where possible. If the element is inside an iframe, obtain its frame locator first:

const frame = page.frameLocator('iframe[title="Payment"]');
await frame.getByRole('button', { name: 'Pay' }).screenshot({ path: 'pay.png' });

The screenshot contains a cookie banner or popup

Dismiss it through the same user flow your application expects, or inject a test-only style after confirming that hiding it will not invalidate the scenario. For third-party overlays, waiting for a stable page state and masking a region can be more reliable than racing a timer.

Fonts or images are missing

Wait for the relevant content, verify that the test environment can reach the asset host, and inspect console and network errors. A navigation completion event does not guarantee that every lazy image or web font has finished loading.

Visual tests fail on another machine

Keep browser version, operating-system fonts, viewport, device scale, locale, and timezone consistent. Disable animations, mask volatile values, and avoid capturing live clocks or randomized data. Pixel output can legitimately differ when any of those inputs changes.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Sale
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【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.

The process runs out of memory

Reduce viewport size or use a clip, choose JPEG/WebP where appropriate, avoid retaining many buffers, and close each browser context. Full-page captures of unusually long documents are inherently expensive.

Browser executable is missing

Run npx playwright install (or install only the browser required by your CI image) and ensure the process has permission to launch it. Pin the Playwright version in your lockfile so local and CI environments use the same browser revision.

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

Performance, reliability, and cost considerations

  • Reuse a browser: launch once and create contexts or pages for multiple captures; launching a new browser for every URL adds overhead.
  • Control concurrency: too many simultaneous pages can exhaust CPU, memory, file descriptors, or the target site’s rate limits.
  • Keep artifacts intentional: save only failure images in routine test runs and retain full-page images for the workflows that need them.
  • Make readiness explicit: deterministic waits usually improve both reliability and runtime compared with large arbitrary delays.
  • Protect secrets: screenshots can contain account data, tokens rendered in the UI, or personal information. Restrict artifact access and mask sensitive locators.

Playwright itself does not charge per screenshot; your costs are the machines, browser runtime, CI minutes, storage, and maintenance of the capture environment.

Or skip the browser setup

ScreenshotNeo is a hosted website screenshot API and MCP server. One GET request returns a PNG, JPEG, WebP, or PDF. It comes first when you need an API because it removes cookie banners, newsletter popups, and chat widgets before capture; only clean shots are billed, while bot checks, blank pages, timeouts, failed loads, and cache hits are not billed. Each response reports the result through X-Page-Verdict and X-Billed headers. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.

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

cURL

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

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)

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

See the complete option list and authentication details in the ScreenshotNeo documentation. It supports full-page and CSS-selector captures, dark mode, device presets and custom viewports, retina scale, PDF paper settings and page ranges, HTML/CSS rendering, custom JavaScript and CSS, clicks, selector or network-idle waits, ad/tracker/request blocking, headers, cookies, user agents, Authorization, timezone, geolocation, transparent backgrounds, resizing, configurable caching, signed image links, asynchronous webhooks, bulk capture of up to 100 URLs per call, a usage API, and an OpenAPI specification. Parameters used by other screenshot APIs also work, which can simplify migration.

The Free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 shots; Growth is $15 for 15,000, Pro $39 for 60,000, Scale $99 for 250,000, and Business $249 for 1,000,000. Yearly billing gives two months free, and every feature is included on every plan. Sign up free to get the 1,000 monthly screenshots without adding a card.

Quick decision guide

Need Use
What a user currently sees page.screenshot()
One very tall document fullPage: true
A component or card locator.screenshot()
A fixed coordinate region clip
Bytes for upload or image diff Omit path and use the returned buffer
Repeatable visual tests Disable animations, mask volatile regions, then use toHaveScreenshot()
Remote capture without browsers to maintain ScreenshotNeo API or MCP server

Frequently Asked Questions

Can Playwright take screenshots in Java?

Yes. Playwright publishes Java screenshot documentation, including the same page, full-page, and element-capture concepts; use the API reference for the Java syntax that matches your installed version.

Does a screenshot prove that all page data loaded?

No. A screenshot records the rendered state at one moment. Add an application-specific readiness check and inspect network or console errors when content is missing.

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.

Which screenshot option should I use for a visual regression baseline?

Use a Playwright Test screenshot assertion, keep the environment consistent, and stabilize animations and volatile regions before accepting the baseline.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

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

Read next

Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.