Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Selenium Screenshots: How-To & Code Examples

· 4 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

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

  1. 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 getScreenshotAs method on the WebDriver or WebElement is sufficient.
  2. Set up your test class. Create a new test file (e.g., ScreenshotTest.java or screenshot_test.py) and import the necessary Selenium classes. In Java: import org.openqa.selenium.*; and import org.openqa.selenium.chrome.ChromeDriver;. In Python: from selenium import webdriver.
  3. 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.
  4. Navigate to your target page. Use driver.get("https://example.com") (Java) or driver.get("https://example.com") (Python) to load the page you want to capture.
  5. Take a full-page screenshot (Java). Cast the driver to TakesScreenshot, call getScreenshotAs(OutputType.FILE), then copy the file to your desired location using Files.copy. Example:
    File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
    Files.copy(src.toPath(), Paths.get("./screenshot.png"), StandardCopyOption.REPLACE_EXISTING);
        
  6. 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, use driver.get_screenshot_as_png() to get the raw bytes.
  7. Capture a specific element (Java). Locate the element (e.g., WebElement el = driver.findElement(By.id("header"))), then call el.getScreenshotAs(OutputType.FILE) and save it as above.
  8. Capture a specific element (Python). Find the element, then call element.screenshot('element.png'). This saves the element's screenshot directly.
  9. 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) or driver.get_full_page_screenshot_as_png() (Python, with specific drivers).
  10. Close the browser. Always call driver.quit() in a finally block (Java) or finally clause (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 WebDriverException if 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) or tearDown method, 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).