Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
Guard the locator before calling screenshot(). Use count() when you only need to know whether a match exists now, isVisible() when a visible element is optional, and waitFor({ state: 'visible' }) (or an assertion) when the element is expected to appear. Call locator.screenshot() only inside the branch that satisfies your policy. A guard is a state check, not a lock: a re-render can detach the node before capture, so best-effort screenshots should handle that race narrowly.
Why an unconditional locator screenshot fails
A Playwright locator represents a query, not a permanent DOM node. locator.screenshot() resolves the element, waits for actionability, scrolls it into view, and captures the element’s bounds. If the locator has no usable element, or the element is detached during that process, the call throws instead of silently producing an empty file.
That behavior is correct for required UI. It is inconvenient for optional panels, feature flags, consent states, A/B variants, and diagnostic captures. Decide first whether absence means “skip” or “fail the test,” then choose a guard that matches that decision.
Choose the guard that matches your timing and policy
| Situation | Guard | When it returns | Absent result |
|---|---|---|---|
| Capture whatever exists at this instant | await locator.count() > 0 |
Immediately after counting matches | Skip |
| Capture only an element visible right now | await locator.isVisible() |
Immediately; it does not wait for visibility | Skip when absent, hidden, or zero-sized |
| The element should appear shortly | await locator.waitFor({ state: 'visible', timeout }) |
After it becomes visible or the timeout expires | Timeout failure unless you deliberately catch it |
| The element is a required contract | await expect(locator).toBeVisible() |
After the assertion passes or fails | Assertion failure with test context |
Playwright defines visible as a non-empty bounding box without visibility:hidden. Its waitFor() method also supports attached, detached, and hidden; hidden includes a detached element, an empty box, or visibility:hidden.
#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
Skip immediately when no match exists
Use count() for a snapshot decision. It is useful when a panel is genuinely optional and you do not want to wait for it.
import { test } from '@playwright/test';
test('capture the optional order summary when present', async ({ page }) => {
await page.goto('https://example.com/checkout');
const panel = page.getByTestId('optional-panel');
if (await panel.count() > 0) {
await panel.screenshot({ path: 'artifacts/optional-panel.png' });
}
});
If the count is zero, no screenshot call is made. count() is not synchronization: the DOM may change between the count and the capture. Use a stable, unique locator so the screenshot describes the intended element rather than an accidental match.
Skip when the element is not visible now
isVisible() is the best-effort branch for an element that may be present but hidden. It returns immediately; its timeout option does not turn it into a wait.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →import { test } from '@playwright/test';
test('capture a visible diagnostic panel', async ({ page }) => {
await page.goto('https://example.com/dashboard');
const panel = page.getByRole('region', { name: 'Order summary' });
if (await panel.isVisible()) {
await panel.screenshot({
path: 'artifacts/order-summary.png',
animations: 'disabled',
type: 'png'
});
}
});
This branch skips a missing, hidden, or zero-sized element. It is appropriate for diagnostics, not for silently bypassing a UI state that the test is supposed to verify.
Wait for an element that should appear
When application behavior says the element should arrive after navigation or an action, wait for it and preserve a timeout failure. A five-second timeout below is an example policy; choose a value appropriate for your application.
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
import { test } from '@playwright/test';
test('wait for and capture the loaded panel', async ({ page }) => {
await page.goto('https://example.com/orders');
const panel = page.getByTestId('optional-panel');
await panel.waitFor({ state: 'visible', timeout: 5000 });
await panel.screenshot({
path: 'artifacts/loaded-panel.png',
animations: 'disabled',
timeout: 5000
});
});
If absence is a legitimate outcome, catch only the timeout and return a result that records the skip. Do not catch every error, because a detached node, an invalid selector, or a browser failure is different from an allowed absence.
import { test } from '@playwright/test';
test('capture an optional panel after a bounded wait', async ({ page }) => {
await page.goto('https://example.com/orders');
const panel = page.getByTestId('optional-panel');
try {
await panel.waitFor({ state: 'visible', timeout: 3000 });
} catch (error) {
if (error instanceof Error && error.name === 'TimeoutError') {
console.info('optional-panel was not visible; screenshot skipped');
return;
}
throw error;
}
await panel.screenshot({ path: 'artifacts/optional-panel.png' });
});
Use assertions when the screenshot proves a requirement
A screenshot should not hide a regression. If the panel is part of the contract, assert it first and let the test fail with useful context.
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Fix the driver behind crashes, sound loss and screen glitches3Repair Windows errors before they cause bigger problemsimport { test, expect } from '@playwright/test';
test('the order summary is required', async ({ page }) => {
await page.goto('https://example.com/checkout');
const panel = page.getByRole('region', { name: 'Order summary' });
await expect(panel).toBeVisible();
await panel.screenshot({ path: 'artifacts/required-order-summary.png' });
});
This separates verification from evidence collection: the assertion decides pass or fail, and the screenshot runs only after the required state exists.
A reusable optional-screenshot helper
Returning a boolean makes the skip explicit to the caller, logger, or test report.
import type { Locator } from '@playwright/test';
export async function screenshotIfVisible(
locator: Locator,
path: string,
): Promise<boolean> {
if (!(await locator.isVisible())) return false;
try {
await locator.screenshot({
path,
animations: 'disabled',
type: 'png'
});
return true;
} catch (error) {
// A re-render can detach the element after isVisible() succeeds.
if (error instanceof Error) {
console.warn(`Optional screenshot skipped: ${error.message}`);
}
return false;
}
}
Use this helper only for best-effort evidence. For required UI, use expect(locator).toBeVisible() and allow failures to surface.
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.
Pick locators that survive page changes
Prefer semantic or intentional test identifiers:
const byRole = page.getByRole('region', { name: 'Order summary' });
const byTestId = page.getByTestId('optional-panel');
Playwright’s locator model is designed for auto-waiting and retry-ability. Role, text, label, placeholder, alt text, title, and test-id locators are available; choose the most reliable unique identifier in your UI. Avoid treating a visibility filter as a substitute for a good locator. If the page can contain multiple similar regions, refine the locator until it identifies the panel you intend to capture.
Free tools Windows power users keep installed
One-click scans. No signup required.
Handle races between the guard and capture
A count or visibility check is a snapshot, not a lock. React, Vue, navigation, or a polling update can replace the node after the check. Keep the guarded capture close together and re-query through the locator rather than storing an ElementHandle.
- For optional evidence, wrap only
locator.screenshot()in a narrowtry/catchand record that the image was skipped. - For required behavior, do not swallow detachment errors; they can indicate a real rendering problem.
- If replacement is expected, wait for the stable state your application exposes, then capture a fresh locator.
Make captures deterministic without masking absence
Screenshot options control output after a valid element has been found. They do not make a missing locator valid.
animations: 'disabled'reduces motion-related differences.stylecan inject a stylesheet for a controlled diagnostic view.typeselects the image format explicitly.timeoutbounds the capture operation.signallets your code abort a capture when its surrounding operation is cancelled.
Use a fixed path per test or worker, and make sure the directory exists before the test writes artifacts. These settings improve repeatability; the guard still determines whether a screenshot is attempted.
Common failures and precise fixes
Timeout while waiting
Cause: The element never reached the requested state within the timeout. Fix: Confirm the locator and application trigger. If absence is allowed, catch only the timeout and report a deliberate skip; otherwise keep the failure.
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallCrashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteRank #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
isVisible() returns false immediately
Cause: The method does not wait. Fix: Use waitFor({ state: 'visible', timeout }) or an assertion when the element is expected later.
Screenshot fails after a successful guard
Cause: A re-render detached or replaced the element between the check and capture. Fix: Treat it as a race for optional diagnostics, retry only under an explicit policy, and preserve the error for required UI.
The wrong component is selected
Cause: A broad text or CSS query matches an unstable or non-unique element. Fix: Prefer a named role or test id and refine it to one intended component.
The image is visually inconsistent
Cause: Animations, late-loading content, or changing styles. Fix: Disable animations, wait for the application’s ready condition, and use a controlled style or explicit type. These changes do not replace the presence guard.
Recommended Free Tools
Performance, reliability, and cost considerations
count() and isVisible() are immediate checks, so they avoid waiting for an element that may never exist. A bounded waitFor() trades that speed for synchronization and can add its full timeout to every legitimately absent case. Capturing only the screenshots you need also reduces artifact storage and review noise. There is no universal performance number: page complexity, browser resources, image size, and network activity determine capture time.
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.
Use skipped images as an intentional result in reports, not as an unexplained missing file. Log the locator’s purpose and the guard that declined it. That distinction lets a reviewer tell an allowed feature variant from a broken test.
Or skip the browser setup
If you only need a clean screenshot of a URL rather than Playwright-level interaction, ScreenshotNeo is the first hosted option to try: it removes common page clutter, bills only clean shots, and its paid entry plan is $5 for 3,000 shots.
One GET request returns PNG, JPEG, WebP, or PDF. The API accepts the URL and access key as query parameters; see the ScreenshotNeo documentation for the complete parameter list.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
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}`);
Before capture, ScreenshotNeo accepts cookie or consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed. Response headers identify the result with X-Page-Verdict and X-Billed.
It also provides an MCP server for Claude, Cursor, and other MCP clients, with take_screenshot, get_page_info, and capture_pdf tools. Other options include full-page capture with lazy images loaded, CSS-selector element capture, dark mode, device presets or custom viewports, retina scale, PDF paper and page controls, custom CSS and JavaScript, pre-capture clicks, hidden selectors, waits for selectors, delays or network idle, request and resource blocking, custom headers, cookies, user agents, Authorization, timezone and geolocation, transparent backgrounds, resizing, TTL-based caching, signed image links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, a usage API, an OpenAPI specification, and compatibility with parameter names used by other screenshot APIs.
| Plan | Allowance | Price |
|---|---|---|
| Free | 1,000 shots per month | $0; no card |
| Starter | 3,000 shots | $5 |
| Growth | 15,000 shots | $15 |
| Pro | 60,000 shots | $39 |
| Scale | 250,000 shots | $99 |
| Business | 1,000,000 shots | $249 |
Every feature is on every plan, and yearly billing gives two months free. Create a free ScreenshotNeo account to get 1,000 screenshots a month with no card.
Decision checklist
- Define a stable, unique locator for the component.
- Decide whether absence is an allowed skip or a test failure.
- Use
count()for immediate attachment,isVisible()for immediate visibility, orwaitFor()/expect()for an expected asynchronous appearance. - Call
screenshot()only after the chosen guard succeeds. - Assume a re-render can still detach the element and handle that race according to your policy.
- Use deterministic screenshot options for diagnostics, without confusing them with presence checks.
Frequently Asked Questions
Can I make a missing locator produce an empty screenshot file?
Do not rely on an empty artifact. Treat absence as an explicit branch and record that the capture was skipped; an empty image would conceal whether the page was blank or the locator never matched.
Should an optional screenshot change the test’s pass or fail status?
Only if the screenshot is part of the requirement. Diagnostic evidence can return a skipped result, while a required element should be asserted and allowed to fail the test.
What should I log when a capture is skipped?
Record the component’s purpose, the guard used, and whether the locator was absent or not visible. This makes an intentional variant distinguishable from a rendering regression.
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.

