October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk5 min

Save Selenium Screenshots with URL-Based Names and Timestamps in Java

Build a safe screenshot filename from a page’s host and path, append an explicit UTC timestamp, then copy Selenium’s captured image to your chosen directory.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Selenium’s TakesScreenshot interface to capture the current browsing context, then build the destination filename yourself from a sanitized URL label and an explicit UTC timestamp. Selenium returns the screenshot; it does not automatically add the page URL or time to the filename.

Save a Selenium screenshot with the URL and timestamp in Java

This Java example captures the current browsing context, labels the file with the page host and path, and appends a UTC timestamp. It creates the output directory and uses millisecond precision in the timestamp.

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

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

public class SaveScreenshot {
    private static final DateTimeFormatter UTC_TIMESTAMP =
            DateTimeFormatter.ofPattern("uuuuMMdd'T'HHmmssSSS'Z'")
                    .withZone(ZoneOffset.UTC);

    public static void main(String[] args) throws IOException {
        String pageUrl = "https://example.com/products/widget?session=private";
        Path outputDirectory = Path.of("screenshots");
        WebDriver driver = new ChromeDriver();

        try {
            driver.get(pageUrl);
            // If the page renders asynchronously, wait for the content you need here.

            Files.createDirectories(outputDirectory);
            String label = urlLabel(pageUrl);
            String timestamp = UTC_TIMESTAMP.format(Instant.now());
            Path destination = outputDirectory.resolve(
                    label + "_" + timestamp + ".png");

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

            System.out.println("Saved screenshot: " + destination.toAbsolutePath());
        } finally {
            driver.quit();
        }
    }

    private static String urlLabel(String value) {
        URI uri = URI.create(value);
        String host = uri.getHost();
        if (host == null || host.isBlank()) {
            throw new IllegalArgumentException("URL must have a host: " + value);
        }

        String path = uri.getPath() == null ? "" : uri.getPath();
        String source = host + path;
        String safe = source.toLowerCase()
                .replaceAll("[^a-z0-9]+", "-")
                .replaceAll("^-+|-+$", "");
        return safe.isBlank() ? "page" : safe;
    }
}

For the example URL, the filename resembles example-com-products-widget_20261003T203416123Z.png. The exact timestamp will vary. Its trailing Z indicates UTC, so filenames can be compared across machines without relying on local timezone settings.

What Selenium captures

Selenium’s WebDriver documentation describes a driver screenshot as a capture of the “current browsing context.” The Java example uses TakesScreenshot, calls getScreenshotAs(OutputType.FILE), and copies the resulting file to an image destination: Selenium WebDriver documentation. The API reference also documents screenshot capture for drivers and HTML elements: TakesScreenshot API, Selenium 4.28.0.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Samsung T7 Portable SSD 1TB Titan Gray, USB 3.2 Gen 2, Up to 1,050MB/s
  • MADE FOR THE MAKERS: Create; Explore; Store; The T7 Portable SSD delivers fast speeds and durable features to back up any endeavor; Build your video editing empire, file your photographs or back up your blogs all in an instant
  • SHARE IDEAS IN A FLASH: Don’t waste a second waiting and spend more time doing; The T7 is embedded with PCIe NVMe technology that brings fast read and write speeds up to 1,050/1,000 MB/s¹, making it almost twice as fast as the T5
  • ALWAYS MAKE THE SAVE: Compact design with massive capacity; With capacities up to 4TB, save exactly what you need to your drive – from large working files to game data and everything in between
  • ADAPTS TO EVERY NEED: Whether using a PC or mobile phone, count on the T7 for extensive compatibility²; It’s a true team player when it comes to heavy-duty application usage or file-saving
  • HI RESOLUTION VIDEO RECORDING: Record Ultra High Resolution (4K 60fs) videos directly onto the T7 Portable SSD with your favorite camera or mobile devices; Supports iPhone 15 Pro Res 4K at 60fps video and more³

Do not assume that a driver-level capture is always a full-document screenshot. If you need just one component, use the element-level capture approach in Selenium’s documentation. For full-page output, verify the behavior supported by the specific browser and driver combination you run.

How the filename is built safely

Use the URL host and path, not the raw URL

The helper parses the URL with java.net.URI, takes its host and path, and replaces characters outside lowercase letters and digits with hyphens. That keeps path separators and awkward filename characters out of the output name. It deliberately omits query strings and fragments: these can make filenames unwieldy and may contain tokens or other sensitive values.

Rank #2
Sandisk 2TB Extreme Portable SSD, Up to 1050MB/s, USB-C, USB 3.2 Gen 2, IP65 Water and Dust Resistance, Updated Firmware, External Solid State Drive, SDSSDE61-2T00-G25
  • Get NVMe solid state performance with up to 1050MB/s read and 1000MB/s write speeds in a portable, high-capacity drive(1) (Based on internal testing; performance may be lower depending on host device & other factors. 1MB=1,000,000 bytes.)
  • Up to 3-meter drop protection and IP65 water and dust resistance mean this tough drive can take a beating(3) (Previously rated for 2-meter drop protection and IP55 rating. Now qualified for the higher, stated specs.)
  • Use the handy carabiner loop to secure it to your belt loop or backpack for extra peace of mind.
  • Help keep private content private with the included password protection featuring 256‐bit AES hardware encryption.(3)
  • Easily manage files and automatically free up space with the SanDisk Memory Zone app.(5). Non-Operating Temperature -20°C to 85°C

If query parameters are essential for distinguishing pages in your workflow, extract only an approved, non-sensitive value and sanitize it separately. Never use arbitrary URL text directly as a filesystem path.

Choose a timestamp and collision policy

The formatter uses UTC and millisecond precision. That is usually more readable than a long fractional timestamp while reducing collisions for sequential captures. If separate jobs can write to the same directory within the same millisecond, add a unique test or run identifier to the filename. The example uses REPLACE_EXISTING; remove that option if overwriting an existing file should instead fail.

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

Keep the extension aligned with the output

OutputType.FILE supplies the screenshot file, and this example names the destination with a .png extension. If you configure or use a different image format, ensure the filename extension matches the actual image format.

Wait for the page state you intend to capture

driver.get() navigates to the URL, but a page can still update after navigation because of asynchronous rendering or lazy content. In production tests, wait for a specific element or state that represents the content you want in the screenshot before calling getScreenshotAs. A fixed sleep may work for a controlled demonstration, but an explicit condition is generally more reliable when load time varies.

Rank #4
Sale
Seagate 2TB Portable Hard Drive | USB 3.0 (STGX2000400)
  • Easily store and access 2TB to content on the go with the Seagate Portable Drive, a USB external hard drive
  • Designed to work with Windows or Mac computers, this external hard drive makes backup a snap just drag and drop
  • To get set up, connect the portable hard drive to a computer for automatic recognition no software required
  • This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable
  • The available storage capacity may vary.

Common errors and fixes

  • The URL label is blank or parsing fails: use an absolute URL with a host, such as https://example.com/page. The helper intentionally rejects hostless input.
  • The screenshot is missing expected content: wait for the relevant element or page state before capture; navigation alone may not mean asynchronous content has finished rendering.
  • The output directory does not exist: the example calls Files.createDirectories before copying. Check that the process also has permission to write there.
  • Files unexpectedly replace one another: filenames can collide if captures share the same URL label and timestamp resolution. Add a run identifier, use finer-grained time, or remove REPLACE_EXISTING to prevent silent replacement.
  • The browser remains running after an exception: keep driver.quit() in a finally block, as in the example, so browser cleanup runs even when capture or file copying fails.
  • The screenshot is not full page: driver capture is documented as the current browsing context, not a universal promise of full-document capture. Check the capabilities of your browser and driver, or capture a specific element if that is what you need.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

ScreenshotNeo can return a screenshot or PDF from a single GET request, without setting up a Selenium browser in your project. Its API and options are documented at ScreenshotNeo documentation.

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

ScreenshotNeo accepts cookie or consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each cleanup step can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and responses identify the page verdict and billing status in headers. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 screenshots.

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

Learn about ScreenshotNeo, or sign up for 1,000 free screenshots a month with no card.

Quick Recap

SaleBestseller No. 4
Seagate 2TB Portable Hard Drive | USB 3.0 (STGX2000400)
Seagate 2TB Portable Hard Drive | USB 3.0 (STGX2000400)
This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable; The available storage capacity may vary.
$119.99
SaleBestseller No. 5
Sandisk 1TB Extreme Portable SSD, Up to 2000MB/s Transfer Speeds-New Model
Sandisk 1TB Extreme Portable SSD, Up to 2000MB/s Transfer Speeds-New Model
IP65 RATING AND UP TO 3M DROP PROTECTION(3) – protects against spills and drops.; POCKET-SIZED – fits easily in pockets and small bags.
$254.24
Best Value
Sale
Sandisk 1TB Extreme Portable SSD, Up to 2000MB/s Transfer Speeds-New Model
  • NEARLY 2X FASTER THAN OUR PREVIOUS GENERATION(8) – move 1,000 high-res photos in under 60 seconds(6) with up to 2000MB/s transfer speeds(2).
  • IP65 RATING AND UP TO 3M DROP PROTECTION(3) – protects against spills and drops.
  • POCKET-SIZED – fits easily in pockets and small bags.
  • SPACE TO OWN YOUR AI CONTENT – speed and capacity to download your high-res clips and photo edits.
  • 256-BIT AES ENCRYPTION(4) – helps keep private files secure with password protection.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

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

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.