Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Scan for outdated or missing drivers - takes under a minute3Clear out junk files and repair common Windows errorsIn a Python Selenium test, save the current browser view with driver.save_screenshot("artifacts/screenshots/test.png"). The method writes a PNG and returns True when Selenium completes the write or False after an I/O failure. Create the destination directory first, use a full path where practical, and check that return value so a failed evidence write cannot hide the original test failure.
Choose the screenshot form before writing test code
Selenium offers three useful outputs. A file is convenient for CI artifacts, bytes are suitable for attachments or image processing, and Base64 is useful when embedding an image in an HTML report.
| Need | Python API | Result |
|---|---|---|
| Current browser window saved directly | driver.save_screenshot(path) |
PNG file and Boolean success value |
| Equivalent file-saving method | driver.get_screenshot_as_file(filename) |
PNG file and Boolean success value |
| One DOM element | element.screenshot(path) |
PNG file for the element and Boolean success value |
| Image in memory | driver.get_screenshot_as_png() |
PNG bytes |
| Report-friendly text | driver.get_screenshot_as_base64() |
Base64-encoded image string |
Use a window capture when context outside one control matters, such as a broken navigation, modal, or layout regression. Use an element capture when the assertion concerns one button, card, table, or form and a smaller artifact is easier to inspect.
Save a window screenshot in a Python Selenium test
Minimal example
from pathlib import Path
from selenium import webdriver
output_dir = Path("artifacts/screenshots")
output_dir.mkdir(parents=True, exist_ok=True)
with webdriver.Chrome() as driver:
driver.get("https://example.com")
saved = driver.save_screenshot(str(output_dir / "example-page.png"))
if not saved:
raise OSError("Selenium could not save the screenshot")
The directory creation is ordinary Python filesystem handling; Selenium does not create missing parent directories for you. The Python file APIs are intended for PNG output, so use a filename ending in .png. The API documentation describes save_screenshot as saving the current window to a PNG image file. It delegates to the file-writing method, which reports an operating-system write failure as False.
#1 Best Overall
- USB-C 2-in-1 storage OTG: The Lexar JumpDrive Dual Drive D40E features USB Type-A and Type-C connectors in a slim, portable form factor for easy device compatibility
- Transfer speeds up to 100MB/s: Based on internal testing, performance may vary depending upon the host device, interface, and usage conditions. 1MB=1,000,000 bytes
- Plug and Play: Widely compatible with USB Type-C smartphones, tablets, laptops, Macs, and traditional Type-A devices, no software installation required. The 360° swivel design allows for easy switching between connectors without the hassle of losing a cap
- Durable & Compact: The Lexar D40E USB memory stick features a metal enclosure, withstands temperatures from 0° to 50° C (32°F to 122°F), and is lightweight at 26g with dimensions of 70.4 x 16.9 x 11.7mm
- Security & Warranty: Securely protects files using an advanced security software solution with 256-bit AES encryption. Backed by a Lexar 3-year limited warranty
Use a deterministic viewport when framing matters
driver.set_window_size(1440, 1000)
driver.get("https://example.com")
if not driver.save_screenshot("artifacts/screenshots/desktop.png"):
raise OSError("Screenshot write failed")
Window dimensions are measured in pixels. Setting them helps keep a test’s intended framing stable, but it does not guarantee pixel-identical images across browsers, operating systems, fonts, graphics settings, or headless environments.
Use a unique name for every run
from datetime import datetime, timezone
from pathlib import Path
stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
path = Path("artifacts/screenshots") / f"checkout-{stamp}.png"
path.parent.mkdir(parents=True, exist_ok=True)
if not driver.save_screenshot(str(path)):
raise OSError(f"Could not write {path}")
A run- or test-specific name prevents parallel jobs from overwriting one another. Your test framework and CI system decide how to upload and retain that directory; Selenium itself does not configure artifact storage or retention.
Capture only the element that matters
Locate the component, then call its screenshot method:
from pathlib import Path
output = Path("artifacts/screenshots")
output.mkdir(parents=True, exist_ok=True)
alert = driver.find_element("css selector", "[role='alert']")
if not alert.screenshot(str(output / "alert.png")):
raise OSError("Element screenshot write failed")
An element image is preferable when the surrounding page is irrelevant or when a compact artifact makes review faster. It also makes the intended evidence explicit: the selector identifies the component whose rendered state matters. If the element is not present, Selenium raises the normal element-location error before the screenshot call; wait for it using the synchronization strategy your test already uses rather than adding an arbitrary delay.
Keep the image in memory
PNG bytes
png_bytes = driver.get_screenshot_as_png()
with open("artifacts/screenshots/current.png", "wb") as image_file:
image_file.write(png_bytes)
This form is useful when a test runner accepts binary attachments, when you need to send the image to another service, or when you want to inspect or transform it before deciding whether to persist it.
Rank #2
- High-speed USB 3.0 performance of up to 150MB/s(1) [(1) Write to drive up to 15x faster than standard USB 2.0 drives (4MB/s); varies by drive capacity. Up to 150MB/s read speed. USB 3.0 port required. Based on internal testing; performance may be lower depending on host device, usage conditions, and other factors; 1MB=1,000,000 bytes]
- Transfer a full-length movie in less than 30 seconds(2) [(2) Based on 1.2GB MPEG-4 video transfer with USB 3.0 host device. Results may vary based on host device, file attributes and other factors]
- Transfer to drive up to 15 times faster than standard USB 2.0 drives(1)
- Sleek, durable metal casing
- Easy-to-use password protection for your private files(3) [(3)Password protection uses 128-bit AES encryption and is supported by Windows 7, Windows 8, Windows 10, and Mac OS X v10.9 plus; Software download required for Mac, visit the SanDisk SecureAccess support page]
Base64 for an HTML report
encoded = driver.get_screenshot_as_base64()
html = f"<img alt='Browser screenshot' src='data:image/png;base64,{encoded}'>"
with open("artifacts/screenshots/report.html", "w", encoding="utf-8") as report:
report.write(html)
Do not confuse these APIs: file methods return a Boolean, the PNG method returns bytes, and the Base64 method returns text.
Capture at the right point in a test
Capture after the state you want to prove
Navigate, perform the action, wait for the expected state, then capture. A screenshot taken before a transition completes can faithfully record an intermediate state and make a correct test look broken. If the evidence is for a failure, capture while the WebDriver session is still open. Once teardown has closed the driver, the driver-bound screenshot methods cannot obtain another image.
Capture on failure without masking the failure
Most test frameworks can run failure hooks, but the hook and CI-upload syntax are framework-specific rather than Selenium guarantees. Keep the screenshot operation defensive: create the directory, generate a collision-resistant name, check the Boolean result, and log a secondary error if writing fails. Do not replace the original assertion exception with an artifact error unless that is an intentional policy.
Choose window versus element evidence
- Window: best for navigation failures, page-level layout, dialogs, and context spread across several regions.
- Element: best for a single control, component, validation message, or visual assertion.
- Both: useful when a component failure may depend on surrounding overlays or responsive layout; capture each with distinct names.
Filesystem and CI reliability
Make paths portable
Use pathlib.Path and convert the path to a string for Selenium. Prefer an absolute workspace path when the test may run from an unexpected working directory. Ensure the process has write permission and that the destination is not a read-only mounted directory.
Preserve artifacts outside the test process
A successful local write does not mean a CI user will be able to download the file. Configure the runner to collect the screenshot directory after the test, including when the test fails. Retention, compression, naming rules, and parallel-worker merging belong to the CI configuration.
Rank #3
- What You Get - 2 pack 64GB genuine USB 2.0 flash drives, 12-month warranty and lifetime friendly customer service
- Great for All Ages and Purposes – the thumb drives are suitable for storing digital data for school, business or daily usage. Apply to data storage of music, photos, movies and other files
- Easy to Use - Plug and play USB memory stick, no need to install any software. Support Windows 7 / 8 / 10 / Vista / XP / Unix / 2000 / ME / NT Linux and Mac OS, compatible with USB 2.0 and 1.1 ports
- Convenient Design - 360°metal swivel cap with matt surface and ring designed zip drive can protect USB connector, avoid to leave your fingerprint and easily attach to your key chain to avoid from losing and for easy carrying
- Brand Yourself - Brand the flash drive with your company's name and provide company's overview, policies, etc. to the newly joined employees or your customers
Prevent misleading evidence
- Use a stable viewport and the same browser mode for comparable runs.
- Wait for the state under test instead of relying on a fixed sleep.
- Give every worker and test a unique path.
- Record the test name, browser, and run identifier in the filename or adjacent metadata.
- Check the Boolean returned by every file-save call.
Common failures and fixes
The method returns False
Selenium encountered an I/O problem while opening or writing the requested file. Verify that the parent directory exists, the path is writable, the filename is valid for the operating system, and the disk or CI workspace is not full. Retry only after correcting the underlying filesystem condition.
“No such file or directory”
The parent directory was not created. Call Path(path).parent.mkdir(parents=True, exist_ok=True) before saving.
Free tools Windows power users keep installed
One-click scans. No signup required.
The file exists locally but is missing from CI
The test process wrote to a workspace that the runner did not archive, or a later cleanup step removed it. Inspect the resolved path in logs and configure CI artifact collection for that directory.
The screenshot shows the wrong page state
The capture ran before navigation, rendering, or an asynchronous update completed. Synchronize on a meaningful element or state, then call the screenshot method. Avoid treating a fixed delay as proof that the page is ready.
The driver is already closed
Move failure capture before driver teardown. A closed WebDriver session cannot provide a new screenshot.
Rank #4
- GOOD VALUE PACKAGE - 1 Pack 32GB Memory Stick USB 2.0 Flash Drives with great cost performance and high quality.
- BIG CAPACITY - The available capacity: 29.10GB-29.8GB, You can save the data of movies, music, photos, designs, programs, manuals, handouts in a high speed.Good performance in digital data storing, transferring and sharing with families, friends, workmates, clients and machines.
- EASY TO USE & PLUG AND WORK - Support windows 7 / 8 / 10 / Vista / XP / 2000 / ME / NT Linux and Mac OS, Compatible with USB2.0 and below.
- TWISTTURN DESIGN & EASY CARRY - The metal clip rotates 360° round the ABS plastic body which with rubber oil skin feeling finish. The capless design can avoid lossing of cap, and providing efficient protection to the USB port.
- WARRANTY & SUPPORT - SIMMAX logo is laser printed on the USB connector surface, our products are of good quality and we promise that any problem about the product within one year since you buy.
Images differ between machines
Viewport size, browser version, operating system, fonts, device scale, and headless behavior can all affect rendering. Set the window size and standardize the environment where possible, while treating identical pixels as an aim rather than a Selenium guarantee.
Or skip the browser setup
If you need a URL image rather than evidence tied to an already-running test session, ScreenshotNeo provides a single-request screenshot API. It accepts consent banners as a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each cleanup step can be disabled. 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. An MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.
See the ScreenshotNeo documentation for request options and authentication. This cURL request saves a WebP image:
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)
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}`);
ScreenshotNeo includes full-page capture with lazy-image loading, CSS-selector element capture, dark mode, 12 device presets plus custom viewports, retina scale, PDF controls, custom CSS and JavaScript, pre-capture clicks, hidden selectors, selector/delay/network-idle waits, request and resource blocking, custom headers/cookies/user agents and Authorization, timezone and geolocation, transparent backgrounds, resizing, configurable-TTL caching, signed public-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.
The Free plan includes 1,000 shots per month with no card. Paid plans start at $5 for 3,000 shots; yearly billing gives two months free, and every feature is available on every plan. Create a free ScreenshotNeo account to try it without a card.
Quick wins for a faster PC:
Scan for outdated or missing drivers - takes under a minuteDriver Scan →Repair Windows errors before they cause bigger problemsFix Now →Cost and performance decisions
Local Selenium screenshots consume the browser session you already run and write to your test workspace, so their practical cost is tied to test runtime, storage, and CI retention rather than a separate screenshot API request. In-memory bytes avoid an intermediate file but still occupy process memory. Large full-window images and long retention periods increase artifact storage; element captures are often smaller.
Best Value
- 【16GB Flash Drive】USB flash drives with 16GB capacity, meet your needs of daily use on work, school, home and travelling for photos, music, videos, files storage and transfer. IMEASON thumb drives can be used to store different files, easy to data backup.
- 【Metal Swivel Cap Design】USB thumb drive is metal swivel cover provides extra protection for the usb thumbdrive connector, no usb drive cap to lose; keychain design makes it easier to carry without worrying lose it.
- 【Wide Compatibility】USB drive supports Windows 7/8/10/11 / Vista / XP / Unix / 2000 / ME / NT Linux and Mac OS, also Supports USB 2.0 and 1.1 ports. USB Stick support TV, desktop, notebook computer, car, audio and other device. The USB Memory Stick is your great data storage and transfer companion with traveling and working.
- 【Easy to use】usb memory stick is plug and play without any software installation. Just simply plug the Flashdrive into the port of your USB-compatible devices such as computer, laptop to start data storage or transmission.
- 【What You Get】16 GB USB Flash Drive Thumb Drive, The default format of the usb storage flash drive is FAT32.
An HTTP screenshot service can separate capture from your test runner and support bulk or asynchronous workflows, but it introduces network latency, authentication, and service-response handling. Choose Selenium when the image must prove the exact state of an interactive test session. Choose an API when you need repeatable URL capture without provisioning a browser in the test process.
Language-binding differences
Selenium documents screenshot examples for multiple bindings, but the storage step differs. Python uses save_screenshot or get_screenshot_as_file; Java uses TakesScreenshot followed by file copying; C# uses GetScreenshot().SaveAsFile(...); JavaScript uses driver.takeScreenshot(), which returns an encoded string. Do not transplant Python return-value assumptions into another binding without checking that binding’s API.
Frequently Asked Questions
Does Selenium save a screenshot as JPEG by default?
The Python file-saving APIs described here are documented for PNG output, so use a .png filename. Convert the image afterward if another format is required.
Can one screenshot prove that a test passed?
No. It is visual evidence of the browser state at one moment; assertions and test results still determine pass or fail.
Should I capture every step?
Usually capture the state needed to diagnose a failure or verify a visual checkpoint. Capturing every step increases runtime and artifact volume, so choose a policy that matches your debugging needs.
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.




