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

Call driver.save_screenshot('artifacts/test-name.png') from the failure path while the WebDriver session is still running. The method captures the current browser window, returns a Boolean, and should be checked before you publish the output directory as a CI artifact.

The reliable pattern

Selenium’s Python WebDriver API provides save_screenshot(filename), documented as saving “a screenshot of the current window to a PNG image file.” Pass a deterministic, writable path ending in .png. A successful call returns True; an I/O failure returns False.

from pathlib import Path


def save_failure_screenshot(driver, test_name: str, output_dir='artifacts') -> Path:
    directory = Path(output_dir)
    directory.mkdir(parents=True, exist_ok=True)
    path = directory / f'{test_name}.png'
    ok = driver.save_screenshot(str(path))
    if not ok:
        raise OSError(f'Could not write screenshot: {path}')
    return path

Use a test name that is safe for your operating system. In a parallel run, include a sanitized node ID, worker name, or another unique value so two tests cannot overwrite the same file.

Save the image from pytest teardown

A fixture teardown is a good place to capture failures because it can inspect the test result and still has access to the live driver. The following conftest.py example records the call-phase report, captures only failed tests, and quits the browser afterward.

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.
import re
from pathlib import Path

import pytest
from selenium import webdriver


def save_failure_screenshot(driver, test_name: str, output_dir='artifacts/screenshots') -> Path:
    directory = Path(output_dir)
    directory.mkdir(parents=True, exist_ok=True)
    safe_name = re.sub(r'[^A-Za-z0-9_.-]+', '_', test_name)
    path = directory / f'{safe_name}.png'
    if not driver.save_screenshot(str(path)):
        raise OSError(f'Could not write screenshot: {path}')
    return path


@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
    outcome = yield
    report = outcome.get_result()
    setattr(item, f'rep_{report.when}', report)


@pytest.fixture
def driver(request):
    browser = webdriver.Chrome()
    yield browser

    call_report = getattr(request.node, 'rep_call', None)
    if call_report is not None and call_report.failed:
        node_id = request.node.nodeid
        save_failure_screenshot(browser, node_id)

    browser.quit()

The screenshot runs before browser.quit(). Quitting first closes the session, so there is no browser window left from which Selenium can capture an image. The hook checks the test’s call phase; setup failures that occur before the driver fixture is created need a separate setup-level strategy because no driver exists yet.

Use a unique and useful filename

Pytest node IDs can contain slashes, brackets, spaces, and parameter values. The example replaces characters outside letters, numbers, underscores, periods, and hyphens. You can also add a timestamp, CI worker identifier, or retry number. Keep the original node ID in the test report or log so the sanitized filename can be traced back to the test.

Publish the directory in CI

A file on a disposable runner disappears when the job ends unless your CI system archives it. Configure the job to upload artifacts/screenshots as a test artifact, including files from failed jobs. This makes the image available after a remote browser worker has been destroyed.

Capture screenshots in other failure paths

Bytes for an HTML report or artifact service

get_screenshot_as_png() returns PNG bytes. This is useful when your reporting system accepts binary attachments instead of a filesystem path.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
png_bytes = driver.get_screenshot_as_png()
with open('artifacts/failure.png', 'wb') as image:
    image.write(png_bytes)

get_screenshot_as_base64() returns Base64 text, which can be embedded in an HTML report or sent to an artifact service. These methods still capture the current browser window; they do not turn the result into a full-page image.

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.

Capture from a unittest-style teardown

If you use Python’s unittest rather than pytest, put the same helper in tearDown, conditionally call it when the test has failed, and call driver.quit() last. The essential ordering is identical: determine failure, save the image, then close the driver.

Plugin or custom hook?

The pytest-screenshot-on-failure package documents a yielded Selenium WebDriver fixture. Its command-line option is:

python3 -m pytest /tests --save_screenshots

By default it writes to a screenshots folder. Set a different folder with --screenshots_dir=<custom_dir_name>. The pytest plugin index also lists this package and pytest-selenium-auto among Selenium-related screenshot plugins.

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.
Consideration Custom hook or fixture Plugin
Lifecycle control You decide exactly which phase counts as a failure and when capture occurs. Uses the package’s fixture and lifecycle conventions.
Names and metadata Easy to include node IDs, parameters, worker names, retries, or build IDs. Uses the package’s naming and output behavior.
Driver compatibility Can match an existing fixture, remote driver, or custom browser factory. Works when your suite matches the documented yielded-driver assumptions.
Parallel safety You control collision-resistant paths and per-worker directories. Verify how the package separates concurrent output before adopting it.
CI integration Place files in the exact artifact directory your pipeline already archives. Configure the plugin’s screenshots directory as a CI artifact.

Choose the plugin when its fixture and command are a close fit. Choose a custom hook when you need a particular filename scheme, per-test metadata, setup for a nonstandard driver, or a prescribed CI layout.

What Selenium captures—and what it does not

  • Current window only: the documented operation captures what is visible in the current browser window.
  • Not automatically full page: do not label the file as a full-page capture unless you add a browser-specific full-page implementation.
  • Current state: capture after the failure has occurred, while the page, URL, console state, and visible error are still present.
  • PNG output: save_screenshot writes a PNG file; use the bytes or Base64 methods when another system needs an in-memory representation.

Common failures and fixes

The file is missing

Check that the parent directory exists and that the test process can write to it. Creating the directory with Path.mkdir(parents=True, exist_ok=True) avoids a common missing-folder error. Also check the Boolean returned by save_screenshot and raise an error when it is False.

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.

The screenshot is overwritten

Two parametrized tests or parallel workers probably generated the same name. Include the full node ID after sanitizing it, and add a worker or retry suffix when your runner can execute the same test concurrently.

No screenshot is produced after a failure

Confirm that the failure hook or fixture teardown is actually running and that it executes before quit(). In pytest, a driver fixture cannot capture a setup failure that occurs before that fixture is constructed. Add handling for that phase only if a browser session is available.

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

The image shows the wrong page

A test may have switched windows, tabs, or frames before failing. Capture the current window deliberately, and switch to the window containing the failure before invoking Selenium’s screenshot method. The API does not infer which tab you intended.

The image is blank or incomplete

The browser may have captured before the page finished rendering, or the failure may have navigated away. Add the waits your test normally uses before the assertion, and capture immediately after the failure while the relevant page remains open. A Selenium window screenshot is not a guarantee that every lazy-loaded or off-screen element is present.

The plugin conflicts with the project fixture

Compare the plugin’s yielded WebDriver fixture with your own fixture scope, browser factory, and teardown order. If the plugin would replace or wrap those assumptions, use the custom hook so your existing lifecycle remains authoritative.

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

Performance, reliability, and artifact hygiene

A screenshot is additional browser I/O on the failure path. Keeping capture conditional means passing tests do not pay that cost. Store images only when needed, use deterministic names, and avoid accidentally retaining an entire workspace of screenshots across repeated local runs.

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

For reliable diagnosis, pair each image with the test node ID, browser and operating-system information already available in your test logs, the URL, and the exception message. The image explains what was visible; the log explains why the assertion failed. Do not treat a screenshot as a substitute for page-source, console, or network diagnostics when those are required.

In CI, archive the screenshot directory even when the job is marked failed. If cleanup runs before artifact collection, the files will be lost. For parallel jobs, either give each worker its own directory or include a worker identifier in every filename.

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

Or skip the browser setup

If you need a clean screenshot of a URL outside the Selenium session, ScreenshotNeo provides a website screenshot API and MCP server. One GET request returns PNG, JPEG, WebP, or PDF. It accepts cookie and consent banners before capture 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, and the response identifies the page result with X-Page-Verdict and billing with X-Billed.

See the ScreenshotNeo API documentation for the complete parameter list. The following calls use the same target URL and save the returned image.

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,
)
r.raise_for_status()
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}`);
if (!res.ok) throw new Error(`Screenshot request failed: ${res.status}`);
const fs = await import('node:fs/promises');
await fs.writeFile('shot.webp', Buffer.from(await res.arrayBuffer()));

ScreenshotNeo also supports full-page capture with lazy images loaded, CSS-selector element capture, dark mode, 12 device presets and arbitrary viewports, retina scale, PDF paper and page-range controls, custom CSS and JavaScript, pre-capture clicks, hidden selectors, waits for a selector, delay, or network idle, blocking ads, trackers, requests, or resource types, custom headers, cookies, user agents and Authorization, timezone and geolocation, transparent backgrounds, resizing, configurable-TTL caching, signed links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, a usage API, and an OpenAPI specification. Parameter names used by other screenshot APIs also work to ease migration.

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.

An MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients, so an AI agent can request captures without you wiring a browser fixture. Every plan includes every feature. The Free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots.

Plan Included shots Price
Free 1,000/month $0
Starter 3,000 $5
Growth 15,000 $15
Pro 60,000 $39
Scale 250,000 $99
Business 1,000,000 $249

Yearly billing gives two months free. For a Selenium failure screenshot that depends on an authenticated, stateful browser session, keep the in-session Selenium helper. For independent URL captures, scheduled checks, PDFs, or AI-agent workflows, the API avoids installing and maintaining a browser in the capture process.

Create a free ScreenshotNeo account to get 1,000 screenshots a month with no card.

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

Frequently Asked Questions

Can I keep the screenshot if the test process crashes immediately after the assertion?

Capture in the fixture or failure hook as soon as the failure is known, then let the CI system archive the directory. A screenshot cannot be recovered after the browser session and worker have both terminated.

Should a failure screenshot replace other debugging artifacts?

No. Keep the image alongside the exception, URL, logs, and any page-source or console data your diagnosis requires; each records a different part of the failure.

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.