Saving Selenium Screenshots on Windows Without Illegal Characters
This guide explains how to avoid Windows filename restrictions when saving Selenium WebDriver screenshots by using a time‑based naming method with safe characters and also provides a custom‑name alternative, complete with Java code examples.
While learning UiAutomator and transferring some of its utilities to Selenium‑Java, the author discovered that Windows does not allow the colon character (":") in file names, causing screenshot‑saving operations to fail.
To store a screenshot with the current timestamp, the following method can be used:
public static void takeScreenshotByNow(WebDriver driver) throws IOException {
File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
String file = "C:\\Users\\user\\Desktop\\" + getNow() + ".png";
FileUtils.copyFile(srcFile, new File(file));
}The getNow() helper formats the date using Chinese characters for hour, minute and second, thereby avoiding the illegal colon:
public static String getNow() {
Date time = new Date();
SimpleDateFormat now = new SimpleDateFormat("yyyy-MM-dd HH点mm分ss秒");
String c = now.format(time);
return c;
}For cases where a specific filename is desired, the author also provides a method that accepts a custom name:
public static void takeScreenshotByName(WebDriver driver, String name) throws IOException {
File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
String file = "C:\\Users\\user\\Desktop\\" + name + ".png";
FileUtils.copyFile(srcFile, new File(file));
}Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
