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

To capture a Selenium screenshot when a test fails, call the WebDriver screenshot method while the browser session is still open, and connect that call to your test runner’s failure hook. In Python with pytest, a pytest_runtest_makereport hook can inspect the test report and save a PNG when the test’s call phase fails. Selenium captures the image; pytest determines when the failure report exists.

The key practical details are making the driver accessible to the hook, choosing which failure phases matter, and ensuring screenshot errors do not hide the original test failure.

How the Selenium and pytest pieces fit together

Selenium’s Python WebDriver offers save_screenshot(path) and get_screenshot_as_file(path) to save the current browser window as a PNG. It can also return PNG bytes or Base64 data for attaching an image to a report instead of writing a file. The Selenium API describes screenshot capture as an interface for drivers or HTML elements that can capture an image and store it in different ways. See the Selenium Python WebDriver API.

Neither screenshot method knows whether a pytest test has failed. pytest creates reports for the setup, call, and teardown phases. Its report hook lets you inspect a report after it is produced and decide whether to collect an artifact. The example below follows pytest’s wrapper-style hook pattern from its basic patterns and examples; the phase names are described in its API reference.

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.

Save a PNG after a failed pytest test

Put the hook and fixture below in conftest.py. This example launches Chrome, makes the driver available on the test item, and captures only failures in the test body (call). Change the fixture to match your project’s browser setup; if you already have a driver fixture, expose that same live driver to the hook rather than opening a second browser.

import re
from pathlib import Path

import pytest
from selenium import webdriver


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


@pytest.hookimpl(wrapper=True, tryfirst=True)
def pytest_runtest_makereport(item, call):
    report = yield
    if report.when != "call" or not report.failed:
        return report

    browser = getattr(item, "driver", None)
    if browser is None:
        return report

    artifact_dir = Path("screenshots")
    artifact_dir.mkdir(parents=True, exist_ok=True)
    # pytest node IDs distinguish parameterized cases; sanitize for filenames.
    safe_name = re.sub(r"[^A-Za-z0-9_.-]+", "_", item.nodeid)
    path = artifact_dir / f"{safe_name}.png"
    try:
        saved = browser.save_screenshot(str(path))
        if not saved:
            print(f"Screenshot write failed: {path}")
    except Exception as exc:
        # Keep artifact-collection failure from replacing the test failure.
        print(f"Screenshot capture failed for {item.nodeid}: {exc}")

    return report

A test using the fixture can request it normally:

def test_homepage_title(driver):
    driver.get("https://example.com")
    assert driver.title == "Expected title"

Run the suite with pytest. On a failed test-body assertion, the hook attempts to write a PNG beneath screenshots/, creating that directory if needed. Make your CI job retain that directory as an artifact if you need to inspect it after the job ends; storage and retention are CI-provider settings, not Selenium behavior.

Why capture during the call report

The hook runs after pytest’s report for a phase is available. For a call-phase failure, the test’s fixture teardown has not yet run, so the driver fixture shown above has not reached browser.quit(). That ordering matters: Selenium must still be able to communicate with the browser session. The report-hook pattern is not a way to resurrect a driver that another fixture or hook has already closed.

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.

Expose the existing driver, not a second one

Many suites create the WebDriver in a fixture, a base test class, or a plugin. The hook needs access to the same driver that displayed the failing page. In the example, request.node.driver = browser is the bridge between a function-scoped fixture and the test item inspected by pytest. If your fixture has another scope or your suite stores the driver elsewhere, adapt this bridge accordingly. Do not create an unrelated browser in the failure hook: it would capture a new page, not the state that failed.

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

Choose whether setup and teardown failures need screenshots

The example filters on report.when == "call", which means it captures an assertion or exception raised while the test body runs. pytest also makes reports for setup and teardown. Those phases need deliberate handling because a driver might not exist yet during setup, or might already have been closed by teardown when its report becomes available.

  • Call failures: Usually the most useful default. The browser fixture is active while the test body runs, so a hook can capture the page before fixture cleanup.
  • Setup failures: Capture only if setup got far enough to create a usable driver and your hook can reach it. A failure before browser initialization has no page to screenshot.
  • Teardown failures: Decide where capture belongs in fixture finalization. The report may be produced after teardown code has run; a hook at that point cannot rely on a still-open browser. If the page state before closing is important, arrange capture in teardown logic before calling quit(), while preserving the original teardown exception.

Changing the phase filter to capture every failed report without considering driver lifecycle can lead to duplicate images or capture attempts after the session is gone.

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.

Use a file, bytes, or Base64 depending on the report

A PNG file is straightforward for CI artifact collection. Selenium also supports retrieving screenshot data as bytes or Base64, which can suit a test report that embeds images. The Selenium API documents the Python methods and their return formats at the WebDriver reference.

When saving directly, check the boolean result: Selenium documents False when the file cannot be written. This can happen if the path is invalid or unwritable. Capture may also raise a WebDriver exception if the session is no longer available or the browser cannot take the image. Record that artifact failure without replacing the assertion or exception that made the test fail in the first place.

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.

Prevent overwritten or unusable screenshot artifacts

A simple filename based only on item.name can collide when tests are parameterized or share a name in different modules. Concurrent pytest workers can also write to the same path. The sample uses item.nodeid and sanitizes it for a filesystem filename, which helps distinguish cases, but parallel workers or repeated runs may still require a worker-specific subdirectory or a unique suffix. Ensure your CI artifact collector picks up the same path where the hook writes.

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
  • Create the destination directory before saving, or handle directory-creation errors as artifact failures.
  • Use filesystem-safe names: node IDs can contain parameter values and characters unsuitable for some operating systems.
  • Keep output paths unique across parameterized cases, modules, retries, and parallel workers.
  • Decide how long CI retains the files and whether retries should replace or preserve earlier attempt images.

A screenshot records visible browser state at the instant it is taken. It does not explain the complete cause by itself. Keep the assertion text and pytest failure output; where useful, collect browser logs or page source as separate diagnostics. pytest’s guidance on flaky tests discusses the value of UI failure screenshots as diagnostic evidence, not as a substitute for understanding the failure.

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

When an existing Java wrapper may be a better fit

If the project is already written in Java and uses Selenide, use its integrations rather than transplanting the Python pytest hook. Selenide documents automatic screenshots for some of its own failed checks, a JUnit 4 ScreenShooter.failedTests() rule, and a TestNG ScreenShooter listener. See Selenide’s screenshot documentation.

That behavior is framework-specific: automatic capture for Selenide checks does not establish coverage for every Java assertion or failure source. Confirm that the integration used by your installed version covers the failures you care about. Selenium’s Java TakesScreenshot API is a separate lower-level option; its version 4.28.0 reference documents capture targets and the possibility of a screenshot exception at TakesScreenshot. Selenium also shows cross-language capture examples in its WebDriver documentation.

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.

Troubleshooting failed Selenium screenshots

No screenshot appears

  • The hook did not run: Confirm conftest.py is in the test’s collection path and the hook uses pytest’s supported wrapper form for the installed pytest version.
  • The hook filtered out the report: The sample captures only call failures, not setup or teardown reports.
  • The driver is missing: Verify the test requests the fixture and that the fixture attaches the live instance to the item the hook receives.

The screenshot is blank, stale, or from the wrong page

  • Wrong driver: Ensure the hook receives the same browser used by the failing test, not another session.
  • Capture happened too late: Move capture ahead of driver shutdown; a closed session cannot provide the relevant page.
  • The page had not reached the expected state: The image only represents what was visible when capture occurred. Use explicit waits in the test before the interaction or assertion when page timing is part of the problem.

The hook reports an I/O or WebDriver error

  • File write failure: Check that the artifact directory exists or can be created, the path is valid, and the process can write there. Treat a false return from save_screenshot() as a failed artifact save.
  • WebDriver exception: Check whether the browser session is still alive and whether another teardown path closed it. Keep exception handling around artifact collection so the test’s original failure remains visible.
  • Files overwrite each other: Include a case-specific name and isolate output by worker or retry where needed.

Or skip the browser setup

If what you need is a fresh screenshot of a public page rather than the exact browser state from a failed Selenium session, ScreenshotNeo can return a page screenshot through one API request. It is not a replacement for capturing the live test browser at the moment of failure; it captures the URL through its own service. See the ScreenshotNeo API documentation.

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

Cookie banners, newsletter popups, and chat widgets are removed before the shot; bot checks, blank pages, and failed loads are never billed. Its MCP server lets AI agents take screenshots. The Free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. Sign up for free and get 1,000 screenshots a month with no card.

Frequently Asked Questions

Can Selenium take a screenshot automatically when an assertion fails?

Selenium provides the capture methods, but automatic capture requires connecting them to a test framework hook, listener, or wrapper that detects failures.

Does this pytest example capture a failed fixture setup?

No. It intentionally captures only the call phase; setup and teardown need separate lifecycle handling.

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

Can I attach a screenshot to a pytest report instead of saving a PNG file?

Yes. Selenium can return screenshot bytes or Base64 data; the report integration must then embed or attach that data.

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.