Selenium Parallel Screenshots Without File Conflicts
In this article
When you run Selenium tests in parallel, multiple threads or processes often try to save screenshots at the same moment. Without coordination, they can overwrite each other's files or crash with "file already exists" errors. This guide shows you how to give every test run a unique, conflict-free filename and directory structure, so your parallel screenshots are always saved safely and traceable back to the test that created them.
What You'll Need
- A Selenium test project (Java, Python, C#, or JavaScript) already set up to run tests in parallel (e.g., TestNG, JUnit, pytest, NUnit, or Mocha).
- Basic knowledge of your test framework's hooks (like
@AfterMethodorteardown). - Access to the test's metadata: test name, class name, thread ID, or timestamp.
Step-by-Step
- Decide on a unique naming scheme. The filename must include at least one element that is guaranteed to differ between parallel runs. Common choices: a timestamp with milliseconds, the thread ID, the test method name, or a random UUID. A combination like
testName_timestamp_threadID.pngworks well. - Create a dedicated screenshot directory per run. Instead of dumping all images into one folder, create a subfolder named with the test run's unique ID (e.g., the timestamp of the suite start). This keeps parallel runs separated and makes cleanup easier.
- Generate the unique identifier once per test. In your test setup (e.g.,
@BeforeMethod), create a string likeString uniqueID = System.currentTimeMillis() + "_" + Thread.currentThread().getId();and store it in a variable accessible to the teardown method. - Use the identifier in the screenshot filename. When you take the screenshot, build the full path as
screenshotDir + "/" + testName + "_" + uniqueID + ".png". Never use a hard-coded filename likescreenshot.png. - Ensure the directory exists before saving. Use
Files.createDirectories(Paths.get(screenshotDir))(Java) oros.makedirs(screenshotDir, exist_ok=True)(Python) to avoidNoSuchFileExceptionerrors. - Wrap the screenshot in a try-catch block. If the file write fails, log the error and continue the test—don't let a screenshot failure fail the whole test run.
- Clean up old screenshots. If you run tests frequently, add a cleanup step that deletes screenshots older than a certain number of days, or clear the folder at the start of each suite run.
Common Mistakes
- Using only a timestamp with second precision. Two tests starting in the same second will collide. Always include milliseconds or a thread ID.
- Hard-coding the file path. This is the #1 cause of overwrites. Always incorporate the unique ID.
- Forgetting to create the directory. Selenium's
getScreenshotAswrites to a file directly; if the parent folder doesn't exist, it throws an exception. - Using the same screenshot directory for all parallel workers. Even with unique filenames, a shared folder can get messy. Use per-run subdirectories.
- Not handling exceptions. If the screenshot fails, the test might abort prematurely. Catch and log instead.
Tips
- Use a library like
java.util.UUID.randomUUID()for a guaranteed unique string—it's overkill but bulletproof. - Include the browser name and version in the folder name if you run cross-browser tests, e.g.,
screenshots/chrome-114/. - For distributed runs (Selenium Grid), include the node ID or hostname in the path to avoid collisions across machines.
- Store screenshots in a temporary folder and only keep the ones you need for reporting—this keeps disk usage low.
- If you use a reporting tool like Allure, attach the screenshot directly to the report instead of saving to disk—this sidesteps file conflicts entirely.
Troubleshooting
- "File already exists" error: Your unique ID is not unique enough. Check if your timestamp has milliseconds or if you're reusing a static variable. Switch to
UUID.randomUUID(). - "No such file or directory" error: The parent directory wasn't created. Add
Files.createDirectories()before saving. - Screenshots are overwriting each other: Verify that your unique ID is generated per test, not per class or per suite. If you store it in a static variable, parallel tests will share it.
- Tests fail randomly with permission errors: On CI systems, multiple workers might be running as different users. Ensure the screenshot directory is writable by all workers.
- Screenshots are saved but empty: The WebDriver might not have finished rendering. Add a small wait (e.g.,
Thread.sleep(500)) before taking the screenshot.
Frequently Asked Questions
Do I need to use a UUID, or is a timestamp enough?
A timestamp with milliseconds plus the thread ID is usually enough for local parallel runs. For distributed runs, add a random UUID to be safe.
Can I save screenshots to a database instead of files?
Yes, you can convert the screenshot to a byte array and store it in a BLOB column. This avoids file conflicts entirely.
How do I take a screenshot of a specific element?
Use element.getScreenshotAs() instead of the driver's method. The same unique naming rules apply.
What if my test framework doesn't have a teardown hook?
You can take the screenshot in the test itself, but ensure the unique ID is generated at the start of the test method.
Is there a way to avoid file conflicts without changing my code?
You could run each parallel worker in a separate Docker container with its own filesystem, but that's heavier than just using unique filenames.
How do I clean up old screenshots automatically?
Use a scheduled job (cron) that deletes files older than N days, or add a cleanup step at the start of your test suite.