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

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

Capture the browser before calling driver.quit(), and keep screenshot failure separate from the test failure. For a one-off operation, put the capture in the relevant exception handler. For a test suite, use the runner’s failure hook or listener so it executes before WebDriver teardown.

The essential pattern: capture first, then re-raise

A Selenium exception does not automatically produce an image. The WebDriver session may still be usable, so request a screenshot while the failing page is on screen. Once the session has been quit, disconnected, or lost, a capture request may fail.

There are four rules that make failure screenshots useful:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Run the screenshot command in the exception path, before cleanup.
  • Write to a known, writable directory and use a full path ending in .png.
  • Check whether the save operation succeeded.
  • Never replace the original Selenium or assertion exception with a secondary screenshot error.

The Python WebDriver API documents save_screenshot(filename) and get_screenshot_as_file(filename) for saving the current window as PNG, plus byte and Base64 methods. See the Selenium Python WebDriver API.

#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

Python: save a screenshot for one failing operation

This complete pattern creates the artifact directory, attempts the capture, records a capture problem if necessary, and then re-raises the original exception. Replace the ellipsis with the actions that may fail.

from pathlib import Path

screenshot_dir = Path("screenshots")
screenshot_dir.mkdir(parents=True, exist_ok=True)

try:
    # Run the browser actions that may fail.
    ...
except Exception as original_error:
    path = screenshot_dir / "failure.png"
    try:
        saved = driver.save_screenshot(str(path))
        if not saved:
            print(f"Selenium could not save screenshot to {path}")
    except Exception as capture_error:
        # Log this separately; do not hide the original test failure.
        print(f"Screenshot capture failed: {capture_error}")
    raise

save_screenshot returns a Boolean. A return value of False indicates an I/O problem, such as an unwritable directory. The same API also exposes get_screenshot_as_file(path); use whichever name fits your codebase, but still check the result.

Use unique names in a test suite

A fixed name such as failure.png is fine for a single script, but parallel or repeated tests can overwrite one another. Build a filename from the test name, an execution identifier, or a timestamp supplied by your runner. Keep the path deterministic enough that the report can link to it.

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.
from pathlib import Path
from datetime import datetime, timezone

name = datetime.now(timezone.utc).strftime("failure-%Y%m%dT%H%M%SZ.png")
path = Path("screenshots") / name
path.parent.mkdir(parents=True, exist_ok=True)

try:
    ...
except Exception:
    try:
        if not driver.save_screenshot(str(path)):
            print(f"Screenshot was not written: {path}")
    except Exception as capture_error:
        print(f"Could not capture {path}: {capture_error}")
    raise

When a file is not the right artifact

For an upload, database, or test-report pipeline, request PNG bytes instead of writing in the browser process:

try:
    ...
except Exception:
    try:
        png_bytes = driver.get_screenshot_as_png()
        upload_to_artifact_store(png_bytes, "failure.png")
    except Exception as capture_error:
        print(f"Screenshot upload failed: {capture_error}")
    raise

get_screenshot_as_base64() is available when the report format expects an encoded string. Bytes and Base64 still represent the current window; they do not make a failed or already-closed session recoverable.

Java: preserve the original exception with TakesScreenshot

In Java, cast the driver to TakesScreenshot and request an output type. Selenium’s Java TakesScreenshot API documents FILE and BASE64 output, and notes that capture can throw WebDriverException or UnsupportedOperationException.

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
import java.io.File;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;

public final class FailureCapture {
    public static void captureAndRethrow(WebDriver driver) throws Exception {
        try {
            // Run the browser actions that may fail.
            runScenario(driver);
        } catch (Exception original) {
            try {
                File screenshot = ((TakesScreenshot) driver)
                    .getScreenshotAs(OutputType.FILE);
                // Copy screenshot to your test artifact or report directory.
                copyToReportDirectory(screenshot);
            } catch (RuntimeException captureFailure) {
                original.addSuppressed(captureFailure);
            }
            throw original;
        }
    }

    private static void runScenario(WebDriver driver) throws Exception {
        // Your Selenium steps go here.
    }

    private static void copyToReportDirectory(File screenshot) throws Exception {
        // Use your build or test-report storage code here.
    }
}

The returned temporary file is not automatically placed in the artifact directory. Copy or otherwise retain it before the test process removes it. If the driver implementation does not support screenshots, the suppressed capture exception documents that fact while the original test exception remains the one reported.

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

Automate capture for every failed test

Wrapping every test body manually becomes repetitive. A test runner’s failure lifecycle hook or listener can centralize the operation, provided it runs before the fixture or suite calls driver.quit().

What the hook must do

  1. Receive the failed test and its still-live driver.
  2. Create a unique artifact path or report attachment.
  3. Attempt the screenshot inside its own error boundary.
  4. Record capture errors as diagnostics, without changing the test’s failure status.
  5. Allow normal teardown to close the driver after the hook finishes.

Framework support is not implied by using Selenium directly. Selenide documents automatic screenshots on failure and integrations for JUnit and TestNG in its screenshots documentation. Use the integration appropriate to your runner and verify its ordering relative to driver cleanup.

Direct handler or failure hook?

Approach Best fit Important consideration
Exception handler around the operation A script or a small number of browser actions Explicitly associates the image with the failing step; protect the original exception from capture errors.
Runner failure hook or listener A suite that needs consistent artifacts for every failed test Use the correct framework integration and execute it before driver teardown. Selenide documents JUnit and TestNG support.

What the screenshot actually shows

Selenium’s screenshot call captures the current browser window. It is not a universal desktop screenshot and does not necessarily include every monitor, browser chrome, or a different window that is not currently selected. If your scenario switched tabs or windows, select the window you want before the failure-prone action, or the artifact may show a different page than expected.

The image is a point-in-time diagnostic. It can reveal an error banner, an unexpected redirect, a missing element, a cookie dialog, or a page that has not finished rendering. It cannot explain a failure that happened before a document was displayed, and it cannot be produced reliably after the session has been terminated.

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

Troubleshooting failed captures

The screenshot call says the session is invalid

Cause: cleanup ran first, the browser crashed, or a remote connection was lost.

Fix: move capture into the exception path or failure hook before quit(). If the browser is already gone, retain the original exception and use other runner logs; do not attempt to mask the failure with a second screenshot error.

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.

The method returns false or no file appears (Python)

Cause: the destination directory does not exist, the process lacks permission, the path is relative to an unexpected working directory, or storage is unavailable.

Fix: create the directory with mkdir(parents=True, exist_ok=True), use an absolute or clearly resolved path, confirm write permission, and check the Boolean result. Keep the .png extension.

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

Java throws WebDriverException or UnsupportedOperationException

Cause: the driver cannot communicate with the browser, or its underlying implementation does not support screenshot capture.

Fix: catch the capture exception, attach it as suppressed or log it, and rethrow the original test exception. Check that the concrete driver in your local or remote environment implements TakesScreenshot.

The artifact is overwritten by another test

Cause: every failure uses the same filename.

Fix: include a test identifier, worker identifier, and/or timestamp in the filename. In parallel execution, give each worker an isolated directory or collision-resistant name.

The image is blank or shows the wrong page

Cause: capture occurred before rendering completed, the wrong window was selected, or the page itself failed to load.

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.
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

Fix: capture at the point of failure, confirm the intended window handle is active, and preserve browser and WebDriver logs alongside the image. A screenshot cannot repair a navigation or rendering failure; it only records what the current window displayed.

A remote grid saved the file somewhere unexpected

Cause: the WebDriver command executes where the browser runs, while your test process may run elsewhere. The API references do not define one universal path behavior for every remote-grid arrangement.

Fix: verify where the remote service stores returned files, or use PNG bytes/Base64 and transfer the data explicitly to your report system.

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

Or skip the browser setup

ScreenshotNeo provides a website screenshot API and MCP server when you need an image of a URL rather than a Selenium session tied to a test. Its clean-shot pipeline accepts cookie and consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the result with X-Page-Verdict and X-Billed headers.

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

Use the API documentation at https://screenshotneo.com/docs/ for authentication and options. A one-call cURL request is:

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

The equivalent Python request is:

import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
    timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)

And 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}`);
if (!res.ok) throw new Error(`Screenshot request failed: ${res.status}`);
const image = Buffer.from(await res.arrayBuffer());
await Bun.write('shot.webp', image);

ScreenshotNeo also offers an MCP server with take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients. Its capture options include full-page screenshots with lazy images loaded, CSS-selector element capture, device presets and custom viewports, retina scale, dark mode, custom CSS or JavaScript, pre-capture clicks, waits, request blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, chosen cache TTLs, signed links, asynchronous webhooks, bulk capture of up to 100 URLs per call, a usage API, and an OpenAPI specification. Parameter names used by other screenshot APIs are accepted to ease migration.

Plan Included screenshots Price
Free 1,000 per month $0, no card
Starter 3,000 $5
Growth 15,000 $15
Pro 60,000 $39
Scale 250,000 $99
Business 1,000,000 $249

Yearly billing provides two months free, and every feature is included on every plan. The free tier includes 1,000 screenshots a month with no card; create a free ScreenshotNeo account to try it.

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.

Operational and cost considerations

  • Capture timing: take the image at the failure point, not during final teardown.
  • Storage: retain the image with the test’s logs, browser version, and exception so a future reader can reproduce the state.
  • Concurrency: use isolated names and directories when workers run in parallel.
  • Failure semantics: screenshot capture is diagnostic; a capture error must not turn into a misleading primary failure.
  • Remote execution: decide whether to return bytes/Base64 or copy a remote file before the session disappears.
  • Hosted URL capture: ScreenshotNeo bills only clean shots; failed loads, bot checks, blank pages, timeouts, and cache hits are identified and not billed.

FAQ

Can I capture a screenshot after calling driver.quit()?

Normally no. Quit ends the WebDriver session, so place the request before teardown and treat any post-quit attempt as best-effort only.

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

Should a screenshot failure fail the test?

The test should remain failed for its original Selenium or assertion error. Record the screenshot problem separately so diagnostics do not obscure the defect being tested.

Which Python method should I choose: a file, bytes, or Base64?

Use a file for ordinary local artifacts, bytes for an upload pipeline, and Base64 when the receiving report or transport requires text encoding.

Frequently Asked Questions

Can I capture a screenshot after calling driver.quit()?

Normally no. Quit ends the WebDriver session, so place the request before teardown and treat any post-quit attempt as best-effort only.

Should a screenshot failure fail the test?

The test should remain failed for its original Selenium or assertion error. Record the screenshot problem separately so diagnostics do not obscure the defect being tested.

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

Which Python method should I choose: a file, bytes, or Base64?

Use a file for ordinary local artifacts, bytes for an upload pipeline, and Base64 when the receiving report or transport requires text encoding.

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.