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.
#1 Best Overall
- 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
- 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.
Rank #3
- Plug-and-play expandability
- SuperSpeed USB 3.2 Gen 1 (5Gbps)
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
- 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.createDirectoriesbefore 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_EXISTINGto prevent silent replacement. - The browser remains running after an exception: keep
driver.quit()in afinallyblock, 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.
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.
Recommended Free Tools
Learn about ScreenshotNeo, or sign up for 1,000 free screenshots a month with no card.
Quick Recap
Best Value
- 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.




