📣 Requestly API Client – Free Forever & Open Source. A powerful alternative to Postman. Try now ->

Screenshots in Selenium WebDriver: Techniques and Examples

Azma Banu
Learn how to capture full-page, element-level, and failure screenshots in Selenium WebDriver with practical examples.
Screenshots in Selenium WebDriver_ Techniques and Examples

Screenshots play an important role in automated testing by helping teams quickly diagnose issues and validate application behavior.

In Selenium WebDriver, capturing screenshots is a widely used practice to verify UI changes, record test outcomes, and provide evidence of failures. A properly designed screenshot strategy not only helps debugging but also strengthens test reporting.

Importance of Capturing Screenshots in Selenium

Screenshots in Selenium tests serve several practical purposes:

  • Debugging failed tests: Provides visual evidence of what went wrong during execution.
  • Validation of UI behavior: Ensures that web elements and layouts render correctly across browsers.
  • Audit and compliance: Screenshots can be used as artifacts for compliance reporting or proof of testing.
  • Communication with stakeholders: Helps non-technical teams understand test outcomes more easily.

Setup Requirements for Screenshot Functionality

Before capturing screenshots, ensure the following setup is in place:

  • WebDriver dependency: Selenium WebDriver must be installed and properly configured.
  • Browser drivers: ChromeDriver, GeckoDriver, or others depending on the browser under test.
  • Testing framework: TestNG, JUnit, or Pytest for managing test execution.
  • File handling libraries: For saving images in desired formats and directories.

In Java, Selenium provides the TakesScreenshot interface; in Python, screenshots can be captured directly using save_screenshot() or get_screenshot_as_file().

Methods to Capture Screenshots with Selenium WebDriver

Selenium provides multiple ways to capture screenshots:

  • In Java:
				
					File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("screenshot.png"));
				
			
  • In Python:
				
					driver.save_screenshot("screenshot.png")
				
			

Both approaches save the current browser state as an image, which can be used for test evidence.

Advanced Scenarios for Using Screenshots

Beyond basic captures, Selenium supports advanced use cases that make screenshots more useful in test automation pipelines.

Live Region RolesFull-Page Screenshot Capture

Some browsers support full-page captures beyond the visible viewport:

				
					driver.get("https://example.com")
driver.get_full_page_screenshot_as_file("fullpage.png")
				
			

This is particularly useful for testing long web pages or scrolling applications.

Capturing Screenshots of Individual Web Elements

Screenshots can be limited to specific elements:

				
					element = driver.find_element(By.ID, "logo")
element.screenshot("logo.png")
				
			

This is helpful when validating images, buttons, or specific UI components.

Taking Screenshots on Test Failures

It is a best practice to capture screenshots only when tests fail:

				
					@AfterMethod
public void tearDown(ITestResult result) {
    if(ITestResult.FAILURE == result.getStatus()) {
        File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(screenshot, new File("failedTest.png"));
    }
    driver.quit();
}
				
			

This ensures test reports contain only relevant failure images.

Handling Multiple Screenshots in a Single Test Run

For scenarios requiring multiple checkpoints:

				
					driver.save_screenshot("step1.png")
# perform action
driver.save_screenshot("step2.png")
				
			

This approach is useful in regression testing or workflows with multiple user actions.

Accessing WebDriver in TestNG Listeners

Listeners in TestNG allow capturing screenshots automatically on failures. Implementing ITestListener makes WebDriver accessible for screenshots.

				
					public void onTestFailure(ITestResult result) {
    WebDriver driver = ((BaseTest)result.getInstance()).getDriver();
    File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
}
				
			

Sharing WebDriver via ThreadLocal or Base Class

When running tests in parallel, sharing WebDriver safely is essential. Using ThreadLocal ensures isolated instances:

				
					private static ThreadLocal<WebDriver> driver = new ThreadLocal<>();
public static WebDriver getDriver() { return driver.get(); }
				
			

This allows screenshots to be taken without conflicts across threads.

Leveraging ITestResult to Attach Test Names to Screenshots

Screenshots should be easily identifiable. With ITestResult, you can name screenshots dynamically:

				
					String testName = result.getName();
FileUtils.copyFile(screenshot, new File(testName + ".png"));
				
			

This makes it easier to track which screenshot corresponds to which failed test case.

Practical Example of Screenshot Implementation in Selenium

A combined Java example with TestNG:

				
					@Test
public void testSearch() {
    driver.get("https://www.google.com");
    WebElement searchBox = driver.findElement(By.NAME, "q");
    searchBox.sendKeys("Selenium WebDriver");
    searchBox.submit();
    Assert.assertTrue(driver.getTitle().contains("Selenium WebDriver"));
}

@AfterMethod
public void captureFailure(ITestResult result) {
    if(ITestResult.FAILURE == result.getStatus()) {
        File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(screenshot, new File(result.getName() + ".png"));
    }
}
				
			

This ensures screenshots are automatically captured when validation fails.

Why run Selenium Tests on BrowserStack?

Running Selenium tests locally limits test coverage to a small set of browsers and devices. BrowserStack Automate provides a real device cloud with over 3500 browser–OS combinations.

Benefits of BrowserStack Automate for Selenium testing:

  • Full cross-browser and cross-device coverage: Test web apps across real environments.
  • Parallel test execution: Run tests at scale to speed up regression cycles.
  • Seamless integration with CI/CD pipelines: Works with Jenkins, GitHub Actions, Azure DevOps, and others.
  • Debugging at scale: Screenshots, video recordings, and logs are captured automatically.
  • No infrastructure overhead: Teams save time and cost by eliminating local lab setup.

Try to take a screenshot in Selenium using the process detailed above. Once mastered, it is simple and requires only a little setup. The benefits far outweigh the minimal effort of writing a few commands. To make things even easier, teams can use BrowserStack’s Screenshot Testing tool, which requires no coding. Simply input a URL, click a button, and instantly receive screenshots across a wide range of real devices and browsers.

  • Screenshot Testing on Real Browsers & Devices: Capture full-page screenshots across iOS, Android, Windows, and macOS at actual device sizes.
  • Screenshot Testing on Local: Validate websites that are hosted locally or behind firewalls.
  • Try Screenshot Testing for Free: Start capturing cross-browser screenshots without writing a single line of code.

By leveraging BrowserStack, Selenium screenshots become part of a scalable, real-world testing workflow that ensures higher test reliability.

Conclusion

Capturing screenshots in Selenium WebDriver is a critical part of building robust automation suites. From basic page captures to advanced scenarios like element-level screenshots and failure-specific images, screenshots enhance both debugging and reporting.

Using TestNG listeners, dynamic naming, and structured WebDriver sharing further strengthens automation pipelines. By running Selenium tests on BrowserStack’s real device cloud, teams can extend this functionality to thousands of real browsers and devices, ensuring complete coverage and reliable results.

Written by
Azma Banu

Related posts