keepcalculator

06 Numbers and Powers

Selenium Screenshots: Add Timestamp to Filename

Card No. 06·55255 · Updated · Standard formula, shown below

This guide shows you how to save Selenium screenshots with a timestamp in the filename, so each capture is uniquely identified and you never overwrite previous screenshots. You’ll learn a simple, reliable method using Python (with Java and JavaScript examples) that works across operating systems.

What You’ll Need

  • A working Selenium setup (Python, Java, or JavaScript) with a WebDriver installed (e.g., ChromeDriver, GeckoDriver).
  • Basic knowledge of your chosen programming language.
  • Access to a code editor or IDE.

Step-by-Step

  1. Import required modules. In Python, import datetime and os. In Java, import java.time.LocalDateTime and java.time.format.DateTimeFormatter. In JavaScript (Node.js), require fs and use new Date().
  2. Generate a timestamp string. Create a string that represents the current date and time in a format safe for filenames. Avoid colons and slashes. For example, in Python: timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S"). In Java: String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));. In JavaScript: const timestamp = new Date().toISOString().replace(/[:.]/g, '-'); (replace colons and dots).
  3. Define the screenshot directory. Create a variable for the folder where screenshots will be saved. For example, screenshot_dir = "screenshots". Ensure the directory exists; if not, create it with os.makedirs(screenshot_dir, exist_ok=True) in Python, Files.createDirectories(Paths.get(screenshot_dir)) in Java, or fs.mkdirSync(screenshot_dir, { recursive: true }) in JavaScript.
  4. Combine directory, timestamp, and filename. Build the full file path. In Python: filepath = os.path.join(screenshot_dir, f"screenshot_{timestamp}.png"). In Java: String filepath = screenshot_dir + "/screenshot_" + timestamp + ".png";. In JavaScript: const filepath = `${screenshot_dir}/screenshot_${timestamp}.png`;.
  5. Take the screenshot and save it. Use Selenium’s built-in method. In Python: driver.save_screenshot(filepath). In Java: File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); Files.copy(src.toPath(), Paths.get(filepath));. In JavaScript: await driver.takeScreenshot().then((data) => fs.writeFileSync(filepath, data, 'base64'));.
  6. Verify the file exists. Optionally, check that the file was created. In Python: print(os.path.exists(filepath)). In Java: System.out.println(Files.exists(Paths.get(filepath)));. In JavaScript: console.log(fs.existsSync(filepath));.
  7. Use a more precise timestamp if needed. If you take multiple screenshots within the same second, add milliseconds. In Python: %Y%m%d_%H%M%S_%f (microseconds). In Java: "yyyyMMdd_HHmmss_SSS" (milliseconds). In JavaScript: new Date().toISOString().replace(/[:.]/g, '-') already includes milliseconds.

Common Mistakes

  • Using colons or slashes in the timestamp. These are invalid in Windows filenames and can cause errors. Always replace them with dashes or underscores.
  • Forgetting to create the directory. If the folder doesn’t exist, the save will fail. Always ensure the directory is created before saving.
  • Overwriting files. If you use a timestamp with only seconds and take multiple screenshots in the same second, the later one overwrites the earlier. Use milliseconds or a counter.
  • Using the wrong path separator. On Windows, use backslashes or forward slashes (Python’s os.path.join handles this). In Java and JavaScript, forward slashes work on all OSes.
  • Not closing the driver. After taking screenshots, always call driver.quit() to release resources.

Tips

  • Use UTC for consistency. If your tests run across time zones, use datetime.datetime.utcnow() (Python) or Instant.now() (Java) to avoid ambiguity.
  • Include a test name. Add a prefix like test_login_ to make screenshots easier to identify.
  • Store screenshots in a dedicated folder. Keep all captures in one place, and optionally clean up old files periodically.
  • Use a helper function. Wrap the screenshot logic in a function to avoid repetition.
  • Log the file path. Print or log where each screenshot was saved for easier debugging.

Troubleshooting

  • FileNotFoundError or NoSuchFileException. The directory doesn’t exist. Create it before saving, or use exist_ok=True (Python) or recursive: true (JavaScript).
  • Invalid filename error. Check for characters like :, /, \, *, ?, ", <, >, |. Replace them in your timestamp.
  • Screenshot is blank or black. The page might not be fully loaded. Add a wait (e.g., WebDriverWait for an element) before taking the screenshot.
  • Permission denied. The directory is read-only or you lack write permissions. Change the directory or run with appropriate permissions.
  • Driver not found. Ensure the WebDriver executable is in your PATH or specify its location when initializing the driver.

Frequently Asked Questions

Can I use the timestamp in the filename in other languages like C#?

Yes, the same principle applies. In C#, use DateTime.Now.ToString("yyyyMMdd_HHmmss") and combine with the directory path.

How do I avoid overwriting screenshots taken in the same second?

Add milliseconds to the timestamp, or append a counter (e.g., _1, _2) if you take multiple shots per second.

Is there a built-in Selenium method to add timestamps?

No, Selenium does not provide this. You must generate the timestamp yourself and pass it to the filename.

Can I save screenshots in a subfolder per test case?

Yes, create a folder for each test case using the timestamp or test name, and save screenshots inside it.

What is the best timestamp format for filenames?

Use YYYYMMDD_HHMMSS (e.g., 20250315_143022) because it sorts chronologically and is human-readable.

Does the timestamp method work with headless browsers?

Yes, it works the same way. Just ensure the headless driver is configured correctly and the directory is writable.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →