Selenium Screenshots: How-To & Code Examples
In this article
Taking screenshots in Selenium is a core skill for test automation, letting you capture visual evidence of test failures, document UI states, or create visual regression checks. This guide walks you through the built-in screenshot methods in Selenium WebDriver, with practical Java and Python code examples you can adapt immediately.
What You'll Need
- A working Selenium WebDriver setup (Java or Python) with a browser driver (ChromeDriver, GeckoDriver, etc.) installed and on your PATH.
- An IDE or text editor to write and run your test scripts.
- Basic familiarity with Selenium commands (finding elements, navigating URLs).
Step-by-Step
- Choose your screenshot method. Selenium offers two main approaches: full-page screenshots (captures the entire scrollable page) and element-specific screenshots (captures just one element). For most cases, the built-in
getScreenshotAsmethod on the WebDriver or WebElement is sufficient. - Set up your test class. Create a new test file (e.g.,
ScreenshotTest.javaorscreenshot_test.py) and import the necessary Selenium classes. In Java:import org.openqa.selenium.*;andimport org.openqa.selenium.chrome.ChromeDriver;. In Python:from selenium import webdriver. - Initialize the WebDriver. Start a browser session. For Chrome in Java:
WebDriver driver = new ChromeDriver();. In Python:driver = webdriver.Chrome(). Make sure the driver executable is accessible. - Navigate to your target page. Use
driver.get("https://example.com")(Java) ordriver.get("https://example.com")(Python) to load the page you want to capture. - Take a full-page screenshot (Java). Cast the driver to
TakesScreenshot, callgetScreenshotAs(OutputType.FILE), then copy the file to your desired location usingFiles.copy. Example:File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); Files.copy(src.toPath(), Paths.get("./screenshot.png"), StandardCopyOption.REPLACE_EXISTING); - Take a full-page screenshot (Python). Simply call
driver.save_screenshot('screenshot.png'). This saves the screenshot directly to the specified path. For more control, usedriver.get_screenshot_as_png()to get the raw bytes. - Capture a specific element (Java). Locate the element (e.g.,
WebElement el = driver.findElement(By.id("header"))), then callel.getScreenshotAs(OutputType.FILE)and save it as above. - Capture a specific element (Python). Find the element, then call
element.screenshot('element.png'). This saves the element's screenshot directly. - Handle full-page scrolling (if needed). The basic screenshot only captures the viewport. For a true full-page capture, you must scroll and stitch images together, or use a tool like AShot (Java) or Selenium's built-in full-page support (available in Selenium 4 with Chrome/Edge). For Selenium 4, use
driver.getFullPageScreenshotAs()(Java) ordriver.get_full_page_screenshot_as_png()(Python, with specific drivers). - Close the browser. Always call
driver.quit()in afinallyblock (Java) orfinallyclause (Python) to release resources.
Common Mistakes
- Forgetting to cast the driver. In Java, you must cast to
TakesScreenshot; otherwise, the method is not available. - Not handling file paths correctly. Using relative paths can lead to files being saved in unexpected directories. Use absolute paths or create the directory first.
- Assuming the screenshot is full-page by default. Most drivers capture only the viewport unless you explicitly use full-page methods.
- Ignoring exceptions. Screenshot methods can throw
WebDriverExceptionif the driver is not in a valid state. Wrap in try-catch. - Using a non-headless browser in CI. In headless mode, screenshots work, but you may need to set a window size to get the desired dimensions.
Tips
- For test failure evidence, take screenshots in an
@AfterMethod(TestNG) ortearDownmethod, but only when the test failed. - Use a timestamp in the filename to avoid overwriting:
String fileName = "screenshot_" + System.currentTimeMillis() + ".png"; - For visual regression, use a library like AShot (Java) or
pixelmatch(Python) to compare screenshots. - Set a consistent window size (e.g.,
driver.manage().window().setSize(new Dimension(1920, 1080))) to make screenshots reproducible. - In headless mode, set the window size explicitly; otherwise, you may get a default 800x600 viewport.
Troubleshooting
- Screenshot is blank or black. This often happens when the page has not fully loaded. Add an explicit wait for the document.readyState to be 'complete' before capturing.
- File not saved. Check that the target directory exists and is writable. In Java, use
Files.createDirectories()if needed. - Element screenshot returns empty. Ensure the element is visible and in the viewport. Scroll it into view with
element.scrollIntoView()(via JavaScript) first. - Full-page screenshot not working in Selenium 3. Upgrade to Selenium 4, or use a third-party library like AShot.
- Permission errors in CI. Use a temporary directory (like
System.getProperty("java.io.tmpdir")) for screenshots and then copy them to an artifact location.
Frequently Asked Questions
Can I take a screenshot of a hidden element?
Yes, but you must first make it visible via JavaScript (e.g., element.style.display = 'block'). Selenium's screenshot of an element requires it to be rendered.
How do I save a screenshot as a base64 string?
Use OutputType.BASE64 in Java: String base64 = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BASE64);. In Python, use driver.get_screenshot_as_base64().
Does Selenium support screenshots in headless mode?
Yes, headless Chrome and Firefox support screenshots. Just ensure you set a window size, as headless mode may default to a small viewport.
Can I take a screenshot of a PDF or a new tab?
Screenshots work on any page in the current tab. For PDFs, the browser may render them as a plugin; you may need to switch to the PDF viewer's frame or use a different approach.
How do I take a screenshot on test failure automatically in TestNG?
Use an ITestListener or an @AfterMethod that checks ITestResult.getStatus() and captures a screenshot if it's FAILURE.
What is the difference between getScreenshotAs and save_screenshot?
In Python, save_screenshot is a convenience method that saves to a file directly. get_screenshot_as_png() returns the image bytes, giving you more control (e.g., to store in memory or upload).