Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
Call driver.save_screenshot("path.png") while the WebDriver session is still running. The method captures the current browser window, returns True when the PNG is written, and returns False for an I/O failure. In a pytest suite, run that call from a failure hook or fixture teardown before driver.quit(), use a unique writable filename, and publish the output directory as a CI artifact.
The direct Selenium operation
Selenium’s Python WebDriver API saves the current window to a PNG file:
ok = driver.save_screenshot("artifacts/login_test.png")
if not ok:
raise OSError("Screenshot could not be written")
The argument should be a complete path ending in .png. This is a viewport screenshot of the current browser window, not an automatic full-page capture. A full-page image requires a separate browser-specific implementation.
A safe helper for failure artifacts
Centralizing directory creation, naming, and error checking keeps the failure path reliable:
#1 Best Overall
- FULL HD IPS DISPLAY - Enjoy vibrant, crystal-clear images with 178-degree wide-viewing angles
- AMD RYZEN 3 30 PROCESSOR - Everyday performance you can count on; Multitask, stream, game casually, and edit photos smoothly with responsive power and vibrant HDR visuals
- ENJOY UP TO 14 HOURS AND 15 MINUTES OF BATTERY LIFE - HP Fast Charge restores battery from 0 to 50% in approximately 45 minutes
- AMD RADEON 610M GRAPHICS - Experience smooth entertainment; Built for streaming and multitasking, enjoy realistic visuals and efficient performance for work and play
- STORAGE AND MEMORY - 512 GB PCIe NVMe M.2 SSD offers fast speed and efficient storage; and 8 GB LPDDR5 RAM memory boosts performance with higher bandwidth
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
Call the helper before the test’s driver is closed. The returned Path can be logged or attached to a test report.
Prevent collisions in parallel runs
Two workers writing test_checkout.png can overwrite one another. Include a sanitized test identifier, pytest node ID, worker ID, or another run-specific value in the filename. Keep path components filesystem-safe: replace slashes, brackets, spaces, and other punctuation that your CI worker does not accept. If the same test can retry, add an attempt number so each failure remains available.
Pytest: capture only when a test fails
A fixture can yield the driver, inspect the test outcome during teardown, take the image, and then quit the browser. The crucial ordering is capture first, quit second.
import re
from pathlib import Path
import pytest
from selenium import webdriver
def safe_name(value: str) -> str:
return re.sub(r"[^A-Za-z0-9_.-]+", "_", value)
@pytest.fixture
def driver(request, tmp_path):
browser = webdriver.Chrome()
yield browser
# Teardown runs while the browser session still exists.
outcome = getattr(request.node, "rep_call", None)
if outcome is not None and outcome.failed:
name = safe_name(request.node.nodeid)
directory = Path("artifacts") / "screenshots"
directory.mkdir(parents=True, exist_ok=True)
path = directory / f"{name}.png"
if not browser.save_screenshot(str(path)):
raise OSError(f"Could not write screenshot: {path}")
browser.quit()
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
setattr(item, f"rep_{report.when}", report)
The pytest_runtest_makereport hook stores the report on the test item. The fixture checks rep_call, so setup and teardown errors are not treated as ordinary call failures by this example. If your suite must also capture setup or teardown errors, choose explicitly which report phases to include and ensure the driver exists for those phases.
Capture from a fixture you already own
If your project has a session, module, or class-scoped driver fixture, put the same outcome check in that fixture’s teardown rather than creating a second browser. Confirm that the fixture scope gives each failed test the correct driver state; a shared driver may have been changed by later steps or reset code.
Rank #2
- Intel Celeron N4120: 4 Cores & Threads, 1.1GHz Base Clock, Up to 2.6GHz Boost Clock, 4MB Cache, Intel UHD Graphics 600. The perfect combination of performance, power consumption, and value helps your device handle multitasking smoothly and reliably with four processing cores to divide up the work.
- 14" HD Display: 14.0-inch diagonal, HD (1366 x 768), micro-edge, anti-glare. See your digital world in a whole new way. Enjoy movies and photos with the great image quality and high-definition detail of 1 million pixels.
- Memory & Storage: 4 GB LPDDR4x & 64 GB eMMC Storage. Adequate high-bandwidth RAM to smoothly run multiple applications and browser tabs all at once. An embedded multimedia card provides reliable flash-based storage.
- Ports:2 x USB 3.0 Type-A,1 x USB 3.0 Type-C,1 x HDMI,1 x Headphone Jack
- Chrome OS: Chromebook is a computer for the way the modern world works, with thousands of apps. Enjoy the seamless simplicity that comes with Google Chrome and Android apps, all integrated into one laptop. It’s fast, simple, and secure.
Use a pytest plugin instead
The pytest-screenshot-on-failure package documents a yielded Selenium WebDriver fixture. Its command is:
python3 -m pytest /tests --save_screenshots
By default it writes to a screenshots directory. Set a different directory with:
Recommended Free Tools
python3 -m pytest /tests --save_screenshots --screenshots_dir=ci_screenshots
A plugin is convenient when its fixture and lifecycle conventions match your suite. A custom hook is the better fit when you need a particular filename, metadata, directory layout, or an existing WebDriver fixture. The pytest plugin index also lists pytest-selenium-auto among Selenium-related screenshot plugins; verify a plugin’s current compatibility with your Selenium and pytest versions before adopting it.
Capturing bytes or Base64 instead of a file
When an HTML report or artifact service accepts data in memory, Selenium can return the image without first writing it to disk:
png_bytes = driver.get_screenshot_as_png()
import base64
png_base64 = driver.get_screenshot_as_base64()
get_screenshot_as_png() returns PNG bytes. get_screenshot_as_base64() returns Base64 text that can be embedded in an HTML report or sent to an artifact service. You still need to perform the call before the session is quit, and you should handle upload or report errors separately from browser capture errors.
Rank #3
- Stunning 15.6" FHD IPS Display: Experience crisp 1920x1080 resolution on this 15.6 inch laptop with an IPS panel that delivers wide viewing angles and vivid colors. The narrow-bezel design maximizes screen real estate for comfortable viewing on this Win 11 laptop, whether you're studying or working.
- Celeron J4105 Processor & 256GB SSD: Powered by a reliable Celeron J4105 processor paired with 12GB DDR4 memory and a fast 256GB M.2 SSD. This laptop computer supports SSD expansion up to 2TB and TF card expansion up to 1TB, so your storage grows with your needs. Delivers smooth multitasking for daily productivity.
- AI-Powered Win 11 Laptop: Built-in AI features enhance your productivity with smart assistance for writing, summarizing, and task management. Pre-installed with Win 11 and includes Office 365 subscription. This student laptop is backed by 1-year warranty and 24/7 customer support.
- All-Day 7000mAh Battery & 180° Hinge: The high-capacity 7000mAh battery keeps this laptop powered through long classes or meetings. The 180-degree lay-flat hinge lets you share your screen effortlessly during presentations. This durable laptop computer adapts to your dynamic workflow.
- Versatile Connectivity Hub: Equipped with USB 3.2, Type-C, Mini HDMI, and 3.5mm audio jack to connect all your peripherals. Stay online anywhere with high-speed 5G WiFi and Bluetooth 4.2. This college laptop keeps you connected at home, in the library, or on the go.
Make the screenshot useful in CI
Create and publish a deterministic directory
- Create the directory before capture; a missing or unwritable parent directory causes the save operation to fail.
- Keep screenshots under the CI system’s artifact path, such as
artifacts/screenshots, rather than a temporary location that is discarded with the worker. - Log the exact path and the test node ID so a failed report can be matched to its image.
- Configure your CI job to upload that directory even when tests fail. Artifact upload commonly needs an “always run” or equivalent condition.
Wait for the state you want to diagnose
A failure screenshot reflects the instant of the call. If an assertion fails before an animation, redirect, or error message finishes, the image may be misleading. Add an explicit Selenium wait for the relevant state in the test itself; do not add a blind delay to every failure unless the application genuinely needs it. A screenshot cannot show content that was never loaded into the current window.
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 →Think about sensitive data
Images can contain account names, tokens displayed by a test page, customer data, or internal URLs. Restrict artifact permissions and retention, and mask sensitive content in the test environment where possible. Treat screenshots as test output, not as disposable console text.
Common failures and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
save_screenshot returns False |
The path is invalid, the parent directory is absent, or the worker cannot write there. | Create the directory, use an absolute or known CI-relative path, check permissions, and fail loudly when the Boolean is false. |
InvalidSessionIdException or a closed-session error |
The capture runs after driver.quit() or after the browser crashed. |
Move capture earlier in teardown. Do not call quit() in a fixture finalizer that runs before your failure hook. |
| No image for an assertion failure | The pytest report was not stored on the item, or the fixture checks the wrong report phase. | Install the pytest_runtest_makereport hook, check rep_call, and decide whether setup and teardown reports also need coverage. |
| Images overwrite one another | Parallel workers or retries use the same filename. | Include the node ID, worker ID, and attempt number after sanitizing them for the filesystem. |
| The file exists locally but not in CI | The directory is outside the artifact configuration or upload runs only on success. | Write beneath the configured artifact directory and make the upload step run on failed jobs too. |
| The screenshot is blank or shows an old page | Capture happened before navigation, rendering, or an expected state transition completed. | Wait for a URL, element, or application state that proves the page is ready, then capture in the failure path. |
| Only the visible viewport is present | The standard Selenium screenshot is a current-window capture. | Use a browser-specific full-page technique if a full document image is a requirement; do not label the ordinary result full-page. |
Performance, reliability, and cost considerations
Taking one PNG only after a failure avoids adding screenshot work to every passing test. The image still consumes disk space and upload time, especially at a high device scale factor or when many workers fail together. Set retention appropriate to your debugging window and monitor artifact-size limits. If you capture Base64 for a report, remember that the encoded representation is larger than the raw PNG and remains in memory until the report is processed.
A screenshot is diagnostic evidence, not proof of the underlying cause. Preserve the exception, stack trace, browser and driver logs, URL, and test node ID alongside it. Those records explain whether the visible state came from an application defect, a synchronization problem, a browser crash, or an environment outage.
Or skip the browser setup
ScreenshotNeo provides a website screenshot API and MCP server for developers. A single request can capture a URL as PNG, JPEG, WebP, or PDF without maintaining a Selenium browser in your test job. For API details, see the ScreenshotNeo documentation.
Rank #4
- Efficient Performance for Everyday Computing: Powered by Intel N150 processor with up to 3.6 GHz Intel Turbo Boost Technology, 6 MB L3 cache, 4 cores, and 4 threads, this HP laptop delivers responsive performance for web browsing, streaming, document editing, and multitasking. Paired with 4GB LPDDR5 RAM and 128GB UFS storage, it handles daily tasks smoothly. Includes 1-year Microsoft 365 Personal subscription for Word, Excel, PowerPoint, and cloud storage to maximize your productivity.
- 14-Inch HD Micro-Edge Display:Enjoy clear visuals on the 14-inch HD (1366 x 768) anti-glare screen with 250-nit brightness and 62.5% sRGB coverage. The micro-edge bezel delivers a 79% screen-to-body ratio in a compact design. An HP True Vision 720p HD camera with noise reduction and dual-array microphones supports clear video calls, remote work, and online learning.
- Modern Connectivity and Wireless Technology: Stay connected with Wi-Fi 6 (2x2) for faster wireless speeds and Bluetooth 5.4 for seamless pairing with accessories. Versatile port selection includes 1 USB Type-C 10Gbps with DisplayPort 1.2 for external displays, 2 USB Type-A 5Gbps ports for peripherals, 1 HDMI 1.4b port, 1 headphone/microphone combo jack, and 1 multi-format SD media card reader. Connect monitors, transfer files quickly, and expand your workspace with ease.
- All-Day Battery Life and Portable Design: Enjoy up to 11 hours of video playback, 7.5 hours of mixed usage, or 7.5 hours of wireless streaming on a single charge, perfect for students and professionals on the go. Weighing just 3.24 lb and measuring 12.76" x 8.86" x 0.71", this lightweight laptop fits easily in backpacks and bags. The stylish willow green top cover with matte finish and natural silver keyboard deck with vertical brushing pattern offer a modern, professional look.
- AI-Enhanced Productivity: Access Microsoft Copilot instantly with the dedicated Copilot key for faster assistance. AI Noise Reduction filters background sounds and improves voice clarity during calls. Dual speakers provide clear audio, while the full-size natural silver keyboard and HP Imagepad support comfortable typing and navigation.
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)
r.raise_for_status()
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 the cookie or consent banner 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 and CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and every response identifies the page verdict and billing status with X-Page-Verdict and X-Billed headers. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.
The service also supports full-page captures with lazy images loaded, CSS-selector element capture, dark mode, 12 device presets or a custom viewport, retina scale, PDF paper sizes and page ranges, HTML/CSS rendering, custom JavaScript and CSS, pre-capture clicks, selector hiding, waits for a selector, delay, or network idle, request and resource blocking, custom headers, cookies, user agents and Authorization, timezone and geolocation, transparent backgrounds, resizing, chosen-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, which can simplify a migration.
The Free plan includes 1,000 shots per month with no card. Paid plans start at $5 for 3,000 shots; every feature is available on every plan, and yearly billing provides two months free. Create an account at ScreenshotNeo’s free sign-up.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.FAQ
Does Selenium save a screenshot as JPEG?
The Python methods described here write PNG output. Convert the bytes with an image-processing tool afterward if another format is required.
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Can I capture a screenshot after calling driver.close()?
Only if another valid window in the same session remains and the driver session is still usable. For failure evidence, capture before closing or quitting the browser.
Should every passing test get a screenshot?
Usually not. Failure-only capture limits runtime, storage, and CI upload overhead while preserving the state that needs investigation.
Best Value
- 【Expansive Display】The 14 Non-touch display offers clear and vibrant visuals, and anti-glare coating, perfect for both work and entertainment.
- Designed for mobility with a slim 0.71-inch profile and lightweight 3.24 lb chassis, making it easy to carry between home, office, school
- 【Versatile Connectivity】Stay connected with multiple ports including USB 3.0 Type-C, USB 3.0 Type-A, HDMI, and a headphone/mic combo jack, along with Wi-Fi and Bluetooth for seamless wireless networking.
- One Year Microsoft 365
What if the browser never starts?
There is no WebDriver window to capture when startup fails. Preserve the startup exception and driver or browser logs; use URL-level capture only when the page can be reached independently of that failed browser session.
Frequently Asked Questions
Does Selenium save a screenshot as JPEG?
The Python methods described here write PNG output. Convert the bytes with an image-processing tool afterward if another format is required.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Can I capture a screenshot after calling driver.close()?
Only if another valid window in the same session remains and the driver session is still usable. For failure evidence, capture before closing or quitting the browser.
Should every passing test get a screenshot?
Usually not. Failure-only capture limits runtime, storage, and CI upload overhead while preserving the state that needs investigation.
What if the browser never starts?
There is no WebDriver window to capture when startup fails. Preserve the startup exception and driver or browser logs; use URL-level capture only when the page can be reached independently of that failed browser session.
The Bottom Line
For Python Selenium, save the current window with driver.save_screenshot(path) before quitting the driver, check its Boolean result, use collision-safe names, and publish the directory as a CI artifact. A pytest hook gives precise control; the plugin is simpler when its fixture conventions fit.
Free tools Windows power users keep installed
One-click scans. No signup required.
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.

