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

Build each filename from a short, sanitized test label plus a UUID generated at capture time, then save it with a .png suffix. For example: checkout-20260929T211800Z-550e8400-e29b-41d4-a716-446655440000.png. The label keeps artifacts understandable; the UUID prevents ordinary overwrites when tests or workers capture screenshots concurrently.

The runtime naming pattern

Selenium accepts the destination filename; it does not select a meaningful, unique artifact name for you. Your test therefore needs to create the directory, generate the name, save the image, and verify the result.

A practical pattern is:

  1. Context label: a short test, page, or failure name such as checkout.
  2. Optional UTC timestamp: an ISO-like value that sorts chronologically.
  3. Random UUID: generated immediately before the capture.
  4. PNG extension: required by Selenium’s Python save APIs.

Use a full path and keep the directory shared only when you deliberately want a common artifact folder. Otherwise, put each CI run or worker in its own directory.

Python: generate and save a unique screenshot

The following uses pathlib for paths and uuid4() for the runtime identifier:

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.
#1 Best Overall
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
from pathlib import Path
from uuid import uuid4

output_dir = Path("artifacts/screenshots")
output_dir.mkdir(parents=True, exist_ok=True)

filename = f"checkout-{uuid4()}.png"
path = output_dir / filename
saved = driver.save_screenshot(str(path))
if not saved:
    raise OSError(f"Could not save screenshot to {path}")

In this example, driver is an already configured Selenium WebDriver. Selenium’s Python WebDriver API documents save_screenshot(filename) and get_screenshot_as_file(filename) as PNG-saving methods. They return False when an I/O error occurs, so treating a false result as a test-artifact failure is safer than silently continuing. The same API documentation recommends a full path and a filename ending in .png.

Python’s uuid documentation describes uuid4() as a randomly generated UUID using a cryptographically secure method. That makes accidental clashes extremely unlikely in normal artifact workflows, but it is not a substitute for checking that the write succeeded.

Add a sortable timestamp when humans inspect artifacts

A timestamp helps people scan a directory, while the UUID handles captures made within the same timestamp interval:

from datetime import datetime, timezone
from pathlib import Path
from uuid import uuid4

run_dir = Path("artifacts/screenshots")
run_dir.mkdir(parents=True, exist_ok=True)

stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
filename = f"checkout-{stamp}-{uuid4()}.png"
path = run_dir / filename
if not driver.save_screenshot(str(path)):
    raise OSError(f"Screenshot write failed: {path}")

Use UTC so names from machines in different time zones sort consistently. A timestamp by itself can repeat when captures occur within the clock’s resolution or on parallel workers; the UUID is the differentiator.

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

Use get_screenshot_as_file when that matches your codebase

If existing tests call get_screenshot_as_file, the same naming strategy applies:

path = output_dir / f"payment-{uuid4()}.png"
if not driver.get_screenshot_as_file(str(path)):
    raise OSError(f"Screenshot write failed: {path}")

Do not omit the boolean check merely because the filename is unique. A unique path can still point to a missing directory, a read-only volume, or a full disk.

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

Java: compose the filename before copying the screenshot

Java Selenium exposes screenshots through the TakesScreenshot interface. This complete example creates the directory, obtains a temporary screenshot file, and copies it to a UUID-based destination:

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;

public final class ScreenshotWriter {
    public static Path save(WebDriver driver, String label) throws IOException {
        Path directory = Path.of("artifacts", "screenshots");
        Files.createDirectories(directory);

        String safeLabel = label.replaceAll("[^A-Za-z0-9._-]", "_");
        Path destination = directory.resolve(
                safeLabel + "-" + UUID.randomUUID() + ".png");

        File temporary = ((TakesScreenshot) driver)
                .getScreenshotAs(OutputType.FILE);
        Files.copy(temporary.toPath(), destination,
                StandardCopyOption.REPLACE_EXISTING);
        return destination;
    }
}

The Java TakesScreenshot API documents getScreenshotAs(OutputType.FILE) as a supported way to obtain a screenshot file. UUID.randomUUID() creates a type-4 UUID with a cryptographically strong pseudo-random generator. The directory must exist before the copy; Files.createDirectories makes that requirement explicit.

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.

The replacement option is safe here because the UUID-based destination is intended to be new. If your policy is “never overwrite,” remove REPLACE_EXISTING and use Files.copy without it; an unexpected existing path will then fail loudly.

Choose the filename components deliberately

Pattern Strength Weakness Use it when
uuid.png Shortest simple unique name Hard to identify by eye Run metadata already identifies the test
label-timestamp.png Readable and naturally sortable Two captures can share a timestamp Captures are serialized and the clock resolution is known
label-timestamp-uuid.png Readable, sortable, and collision-resistant Longer names General-purpose CI and local debugging
run-test-worker-uuid.png Groups artifacts by run and parallel worker Requires stable run metadata Many workers write to one artifact store

Keep labels short and sanitize them for the target filesystem. Replace slashes, colons, control characters, and other platform-specific separators. Do not put passwords, access tokens, session IDs, email addresses, or other personal data in a filename; artifact names are often exposed in CI logs and reports.

Make parallel and repeated runs predictable

Separate runs when possible

The cleanest layout is a run-specific directory, followed by a worker or browser name:

artifacts/
  run-1842/
    worker-03/
      checkout-20260929T211800Z-...png

A UUID still protects against accidental duplication inside that directory, while the hierarchy makes retention and cleanup easier. If your CI system already groups artifacts by run, a shorter filename such as checkout-<uuid>.png is sufficient.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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.

Include test identity, not only a worker ID

A worker number helps locate a failure but does not guarantee uniqueness: a worker can capture several screenshots, and workers can be reused on later runs. Include a test or case label and keep the UUID as the final differentiator.

Do not rely on wall-clock uniqueness

Machine clocks can have different offsets, and two processes can format the same second or millisecond at once. Use timestamps for sorting, not as the uniqueness mechanism. If an external system supplies a run ID, use it as context rather than replacing the UUID.

Verify writes and handle failures

Python checks

Check Selenium’s boolean result, then optionally confirm that the resulting file is non-empty:

if not driver.save_screenshot(str(path)):
    raise OSError(f"Selenium reported an I/O error: {path}")
if not path.is_file() or path.stat().st_size == 0:
    raise OSError(f"Screenshot is missing or empty: {path}")

The size check catches storage or pipeline problems that occur after the API call returns. It is a validation guard, not a guarantee that the image contains the expected page.

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

Java checks

Files.copy throws an IOException for common path and storage failures. Let that exception fail the artifact step or wrap it with the test name and destination so the CI log identifies the exact file. If a test can continue without screenshots, catch it at the reporting boundary rather than silently discarding the error in the capture helper.

Directory and permission failures

  • Create the directory once before the first capture, not after a failure.
  • Use an absolute workspace path when the test runner’s current directory is uncertain.
  • Check that the CI user can write to the workspace and that the volume has free space.
  • On Windows, avoid reserved names and excessive path length; shorten the label or move run identity into parent directories.

Troubleshooting unique screenshot names

Files still overwrite

Inspect the final path, not just the label. A fixed directory plus a timestamp-only name, a test fixture that resets the UUID, or a cleanup step that runs during the test can all make files appear to overwrite. Log the complete path immediately before saving and confirm that each capture generates a new UUID.

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

The save method returns False (Python)

This indicates an I/O error according to Selenium’s Python API. Verify that the parent directory exists, the path is writable, the filename ends in .png, and the process has not exhausted disk space. Use a full path to avoid a different working directory than the one you expect.

Java throws IOException

Check directory creation, permissions, free space, and whether the destination is on a mounted or temporary volume that disappeared. Also ensure the object really implements TakesScreenshot; the screenshot call and file copy are separate operations, so report which one failed.

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

Names contain illegal characters

Sanitize only the human label. Keep the UUID’s hyphens and the .png extension unchanged. A conservative ASCII label pattern such as letters, digits, dot, underscore, and hyphen works across common CI operating systems.

The image is blank or captures the wrong state

Unique naming cannot correct browser timing. Wait for the page or target element before calling the screenshot method, and capture after the action whose result you are diagnosing. If the file exists and is non-empty but visually wrong, investigate WebDriver synchronization rather than filename generation.

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

Performance, retention, and cost considerations

Generating a UUID and formatting a filename is negligible compared with browser rendering and PNG encoding. The practical costs are disk space, artifact upload time, and retention. Capture on failures or at deliberate checkpoints, compress or resize only in a post-processing step that preserves the original when it matters, and configure CI retention so thousands of retries do not accumulate forever.

For parallel suites, avoid a single global counter unless you also coordinate access between processes. A counter can be useful inside a run-specific directory, but the UUID approach requires no lock and remains safe when workers start at the same time. No published collision percentage is needed for this design: the UUID APIs provide random identifiers, while the application still checks write success and manages storage.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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.

Or skip the browser setup

If you need a URL image or PDF rather than a screenshot tied to an existing Selenium session, ScreenshotNeo provides a single-request capture API and an MCP server for AI agents. It accepts consent banners like 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.

See the ScreenshotNeo API documentation for the complete option list. The service supports full-page captures with lazy images loaded, CSS-selector element shots, dark mode, 12 device presets or custom viewports, retina scale, PDF paper size/margins/landscape/page ranges, HTML/CSS rendering, custom JavaScript and CSS, pre-capture clicks, hidden selectors, selector/delay/network-idle waits, ad and tracker blocking, custom headers/cookies/user agents/Authorization, timezone and geolocation, transparent backgrounds, resizing, configurable-TTL caching, signed links, asynchronous jobs with signed webhooks, up to 100 URLs per bulk call, a usage API, an OpenAPI specification, and familiar parameter names for easier migration.

One GET request with 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)
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}`);

Every feature is included on every plan. The Free plan includes 1,000 shots per month with no card; paid plans are Starter $5 for 3,000, Growth $15 for 15,000, Pro $39 for 60,000, Scale $99 for 250,000, and Business $249 for 1,000,000. Yearly billing provides two months free.

Sign up for ScreenshotNeo to get 1,000 screenshots each month without a card.

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

Frequently Asked Questions

Can I intentionally reuse a filename for visual baselines?

Yes. A baseline comparison may deliberately use a deterministic name such as checkout-home.png. Keep that baseline directory separate from runtime failure artifacts, where UUID names prevent one test run from replacing another.

How can I keep metadata without making filenames unwieldy?

Store a small JSON or CSV manifest beside the images. Record the generated filename, test ID, URL, browser, worker, and timestamp there; keep the on-disk label short and filesystem-safe.

Does the UUID change the screenshot format?

No. The identifier only changes the destination name. Selenium’s screenshot API writes the PNG representation, and the .png suffix keeps the artifact type explicit.

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.

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