Selenium Screenshot Consistency: Full Guide
In this article
This guide explains how to make Selenium screenshots look identical across different runs, operating systems, and browsers. You'll learn to control viewport size, manage dynamic content, handle animations, and stabilize timing so your visual regression tests compare cleanly.
What You'll Need
- A working Selenium setup (WebDriver for your browser)
- Basic knowledge of your test framework (JUnit, TestNG, pytest, etc.)
- Optional: a visual regression tool like Applitools, Percy, or a simple image diff library
Step-by-Step
- Set a fixed viewport size before every test. Browser window dimensions directly affect layout. Use
driver.manage().window().setSize(new Dimension(1366, 768))or the equivalent in your language. Set this at the start of each test, not just once in a setup method, because some tests or prior runs may resize the window. - Disable animations and transitions. CSS animations, hover effects, and transitions change pixel output between frames. Inject a style tag that kills them all:
driver.executeScript("document.body.style.transition='none'; document.body.style.animation='none';");
For thorough coverage, also add a global CSS rule viadriver.executeScriptthat sets* { transition: none !important; animation: none !important; }. - Wait for network requests to finish. Lazy-loaded images, fonts, and API calls can finish after the page loads. Use Selenium's
WebDriverWaitto wait fordocument.readyState === 'complete', then additionally wait for any AJAX spinner or skeleton loader to disappear. A fixed sleep of 2–3 seconds is a fallback but not a guarantee. - Freeze dynamic content. Dates, timers, rotating carousels, and live counters change every run. Replace them with static values via JavaScript before capturing. For example, set all elements with class
timestampto a fixed string, or usedriver.executeScriptto overwriteDate.nowandMath.randomwith deterministic stubs. - Hide or standardize the cursor. The mouse pointer position can appear in screenshots if you're capturing the full page. Move the cursor to a corner with
new Actions(driver).moveByOffset(0, 0).perform()or hide it with a CSS rule* { cursor: none !important; }. - Use the same browser and version across runs. Chrome 120 renders differently than Chrome 121 or Firefox. Pin your WebDriver to a specific browser version, ideally via a Docker container or a version manager like Selenium Manager. Document the exact version in your test config.
- Match the device pixel ratio. If you run tests on machines with different display scaling (e.g., 100% vs 125% Windows scaling), screenshots will differ. Set a fixed device scale factor in Chrome options:
--force-device-scale-factor=1. - Disable hardware acceleration and GPU rendering. These can cause minor anti-aliasing differences. Add browser flags like
--disable-gpuand--disable-software-rasterizerin headless mode. For Chrome, also consider--hide-scrollbarsto keep scrollbar width consistent. - Take full-page screenshots with a fixed capture method. Different tools (Selenium's built-in, CDP, or third-party) handle full-page captures differently. Pick one method and stick to it. For example, use
driver.executeScript("return document.body.scrollHeight")to get height, then resize the window to that height before capturing—this avoids the inconsistent behavior offullPageScreenshotacross browsers. - Run in a clean profile. Browser extensions, saved passwords, or a changed default font can alter rendering. Launch with a fresh, temporary profile:
--user-data-dir=/tmp/clean-profilefor Chrome, or use a fresh Firefox profile. Delete the profile directory after each run. - Standardize the base URL and test data. If your page shows user-specific content (e.g., "Hello, John"), ensure every run uses the same test account and the same URL. Reset the database or use a mock API before each test to guarantee identical data.
- Add a small settle delay after all waits. Even with everything above, fonts may swap or images may decode late. A 500ms fixed sleep immediately before the screenshot, after all other waits, catches these edge cases without slowing tests too much.
- Capture and compare in the same format. Save screenshots as PNG (lossless). If you're diffing, use a tool that handles anti-aliasing tolerance. Set a pixel-diff threshold (e.g., 0.1% of pixels) to ignore sub-pixel rendering differences.
Common Mistakes
- Setting viewport size in setup only. If a test navigates to a new page or opens a new window, the size may reset.
- Ignoring web fonts. Fonts load asynchronously. If you don't wait for
document.fonts.ready, screenshots may use fallback fonts on slow runs. - Using
Thread.sleep()as the only wait. Fixed sleeps are brittle—sometimes too short, sometimes unnecessarily long. Combine them with explicit waits. - Forgetting about scrollbars. A scrollbar can appear or disappear based on content height, shifting layout by 15–20 pixels. Hide them with CSS or browser flags.
- Mixing headless and headed modes. Headless browsers often render slightly differently (font smoothing, subpixel positioning). Pick one mode for all baseline and comparison runs.
Tips
- Run your visual tests in a Docker container with a fixed OS and browser version to eliminate host-machine differences.
- Use a baseline image stored in your repo. On each run, compare against that baseline, not against the previous run.
- If you use a cloud visual testing service, it handles many of these inconsistencies for you—but you still need stable waits and data.
- For element-level screenshots, scroll the element into view first with
scrollIntoView()and ensure it's fully within the viewport before capturing. - Log the browser version, viewport size, and OS in your test report so you can reproduce failures.
- Consider using Selenium's CDP (Chrome DevTools Protocol) for more precise control over rendering, like disabling image loading entirely if images aren't part of what you're testing.
Troubleshooting
Screenshots still differ between runs. Start by diffing the two images visually to identify the changed region. If it's a small strip at the bottom, it's likely a scrollbar or lazy-loaded content. If it's a whole section, check for animations or dynamic data. Add more explicit waits and re-check your CSS injection.
Fonts look different. Ensure you're waiting for document.fonts.ready and that the same font files are available (no local font substitution). In headless mode, install the same fonts on the machine or use a Docker image with them pre-installed.
Images load inconsistently. Use a network throttle or wait for all img elements to have complete === true and naturalWidth > 0. Alternatively, block image requests entirely with CDP if images aren't part of the test.
Viewport size is ignored. Some browsers ignore setSize in headless mode. Use the browser option --window-size=1366,768 instead, or both together.
Timing still varies. If you're seeing occasional flakiness, increase the settle delay to 1 second. If that doesn't help, capture the screenshot twice and compare—if the two captures differ, your page is still changing; find the source.
Cross-OS differences persist. Windows, macOS, and Linux render fonts and anti-aliasing differently. If you can't use Docker, at least standardize the OS across all runs, including your baseline generation.
Frequently Asked Questions
Q: Do I need a visual regression tool, or can I just compare images manually?
A: Manual comparison works for a few screenshots, but automated diffing (even a simple pixel-diff script) is essential for more than a handful. Tools like Percy or Applitools add smart handling of anti-aliasing and dynamic regions.
Q: Why do my screenshots differ between headless and headed mode?
A: Headless browsers often disable font smoothing and use different GPU settings. Always generate baselines in the same mode you run comparisons in.
Q: How long should I wait before taking a screenshot?
A: There's no universal number. Wait for document.readyState, then for any AJAX indicators, then for fonts, then add a 500ms settle delay. If you still see flakiness, increase it.
Q: Can I ignore small pixel differences?
A: Yes, most diff tools support a tolerance threshold. A common approach is to allow up to 0.1% of pixels to differ, or to ignore differences below a certain color distance (e.g., RGB delta of 10).
Q: What if my page has a video or canvas element?
A: Videos and canvases are inherently dynamic. Pause the video via JavaScript, and for canvas, either stub the drawing calls or exclude that region from comparison.
Q: Should I test on multiple browsers?
A: Yes, but generate separate baselines for each browser. Cross-browser consistency is a goal, but you'll still see minor differences—each browser needs its own baseline.