
If something breaks in your production queue at 2AM, it’s hard to make out where the bug is. With a screenshot in Selenium, you can easily stack trace, catch code mismatches, and rectify the mistake without involving other testers at large.
Screenshots in Selenium provide a visual trail of application behavior during execution, making it easier to identify failures, UI issues, or inconsistencies.
It can capture app bugs (like telling you that a checkout button is missing in text execution), eliminate manual test reruns, and give documented visual proof that your website works accurately.
In this guide, you will learn all about how to take screenshots in Selenium, various examples, listeners, best practices, and industry-wide applications.
Run Selenium Tests on Cloud
A screenshot in Selenium testing is a method to visualize new bugs that popped up after a test execution cycle through a dedicated image.
It follows pixel matching to compare the previous Selenium script with the current one after every regression for testers to evaluate how the changes caused the code to misbehave.
It also differentiates flaky tests (late page rendering or locator issues) from real app bugs like faulty login, missing checkboxes, or unresponsive UI.
Routine behavior checks do not capture what the page actually looked like at a given moment, but taking full-page screenshots of code gives proper bug details.
Here is why screenshots in Selenium allow you to trace for bugs and maintain compliance.
Screenshots in Selenium help diagnose test failures, provide visual evidence for bug reporting, and ensure UI consistency across browsers.
The most common way to take a screenshot is via the TakesScreenshot class, which is built into Selenium WebDriver. It captures a viewport state and saves it as an image file to match with previous code later on.

Here is the basic screenshot syntax you will use in almost every implementation:
File screenshot = ((TakesScreenshot) driver). getScreenshotAs(OutputType.FILE);FileUtils.copyFile(screenshot, new File("screenshot.png")); Here is what is happening in this screenshot in the Java code snippet:
In practice, you do not need a screenshot after every new regression test for the application. Screenshots are required if testers observe a difference in behavior across different test environments.
To capture a screenshot, initialize a TestNG listener as soon as a test execution fails. A listener allows screenshot integration with minimal effort. When a test run fails, it automatically captures an image of the browser window.
With ITestListener, screenshots can be automatically added to reports.
public void onTestFailure(ITestResult result) {
File screenshot = ((TakesScreenshot) driver). getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("failure_" + result.getName() + ".png"));
}This method runs automatically and captures a baseline snapshot if a test fails, giving you an idea of the type of bugs encountered.
This pattern, utility class + listener, is what the rest of this guide builds on for structured, automated screenshot capture across a full test suite.
To take a screenshot using Selenium WebDriver using Java, you must cast your WebDriver instance (server layer) to the TakesScreenshot interface to build a relation. The WebDriver instance fires up the browser session, while TakesScreenshot captures a snap.
Here are the steps to do that.
Step 1: Cast the driver to TakesScreenshot
WebDriver is an intermediary between the Selenium script and the server and doesn’t directly trigger a screenshot. Users need to cast it to the TakesScreenshot interface.
takesScreenshot ts = (TakesScreenshot) driver; This works with ChromeDriver, Firefox Driver, and most other WebDriver implementations. Since they all implement TakesScreenshot under the hood.
Step 2: Choose an Output Type
The getScreenshotAs() is used to know what format you want your image file to be in.
File screenshotFile = ts.getScreenshotAs(OutputType.FILE);
String base64Screenshot = ts.getScreenshotAs(OutputType.BASE64);
byte[] screenshotBytes = ts.getScreenshotAs(OutputType.BYTES);Step 3: Save or use the result
If you used OUTPUTType.FILE, the screenshot image will get deleted once you exit the Java virtual machine (JVM) compiler. So it must be copied to a permanent location using Apache Common’s IO’s FileUtils:
FileUtils.copyFile(screenshotFile, new File("output/homepage.png")); If you used the BASE64 or BYTES file instead, no copying is needed. You can use the string or byte array directly and embed the image in the HTML report.
For most test automation, OutputType. FILE is the standard choice since it produces a standalone image file you can attach to reports or bug tickets. Reach for BASE64 only when you specifically need the image embedded inline rather than as a separate file.
Step 4: Generating Screenshots on Test Failures
With Java and TestNG, screenshots can be triggered automatically when a test fails.

This can be achieved through listeners (ITestListener) that hook into the test lifecycle.
public void onTestFailure(ITestResult result) {
File screenshot = ((TakesScreenshot) driver). getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("failure_" + result.getName() + ".png"));
}Note: A failure can be intentional or non-intentional. It is vital to compare the screenshot against the baseline and evaluate whether the failure is genuine or just environment-related.
Read More: How to Annotate Screenshots
Before capturing screenshots, make sure that the environment is correctly configured. The essential step includes.
Sample Maven dependency for Selenium:
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.12.0</version>
</dependency> The TakesScreenshot interface helps capture screenshots of browser sessions by interacting with Selenium WebDriver. Not every WebDriver implementation supports screenshots, so Selenium offers this as a separate interface rather than building it into WebDriver directly.
The following are the standard approaches:
There are various methods that you can use with TakesScreenshot to manage the image file:
Selenium's C# bindings use the ITakesScreenshot interface concept, which is the equivalent of the TakesScreenshot interface in Java.
Basic screenshot capture:
ITakesScreenshot screenshot = (ITakesScreenshot)driver;
Screenshot ss = screenshot. GetScreenshot();
ss.SaveAsFile("screenshot.png", ScreenshotImageFormat.Png);Capturing on test failure (with the NUnit package)
Here is how you can take a screenshot whenever a test execution fails in C#.
[TearDown]
public void TearDown()
{
if (TestContext.CurrentContext.Result.Outcome.Status == TestStatus.Failed)
{
ITakesScreenshot screenshot = (ITakesScreenshot)driver;
Screenshot ss = screenshot.GetScreenshot();
string fileName = $"failure_{TestContext.CurrentContext.Test.Name}_{DateTime.Now:yyyyMMdd_HHmmss}.png";
ss.SaveAsFile(fileName, ScreenshotImageFormat.Png);
}
driver.Quit();
}NUnit’s TestContext exposes the test pass/fail test that initializes the GetScreenshot method. Similar to the TestNG listener in Java, this checks the outcome and then triggers the screenshot.
Python's Selenium bindings simplify this further. Screenshot methods are built directly onto the WebDriver object, with no casting or interface required.
1. Basic screenshot capture in Python:
driver.save_screenshot("screenshot.png") Thats the entire call which enables testers to click screenshot directly form the webDriver of the live browser session.
2. Getting screenshot data without saving to disk:
screenshot_bytes = driver.get_screenshot_as_png()
screenshot_base64 = driver.get_screenshot_as_base64()These methods are useful if you want to check images quickly. It helps you embed the images in the HTML report iself.
3. Capturing on test failure (pytest example)
Here is how you can trigger snapshots to check what’s wrong with code if test fails:
import pytest
import time
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome. get_result()
if report.when == "call" and report. failed:
driver = item.funcargs["driver"]
filename = f"failure_{item.name}_{int(time.time())}.png"
driver.save_screenshot(filename) This uses a pytest hook (pytest_runtest_makereport) to check whether the test failed, then captures a screenshot with the test name and timestamp; Python's equivalent of the Java ITestListener / C# TearDown pattern.
Selenium’s default capability captures only the visible viewport. For full-page screenshots:
Code example with AShot:
import org.openqa.selenium.WebDriver;
import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import ru.yandex.qatools.ashot.shooting.ShootingStrategies;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
private static final int SCROLL_TIMEOUT_MS = 1000;
public void captureFullPage(WebDriver driver, String fileName) throws IOException {
Screenshot screenshot = new AShot()
.shootingStrategy(ShootingStrategies.viewportPasting(SCROLL_TIMEOUT_MS))
.takeScreenshot(driver);
ImageIO.write(screenshot.getImage(), "PNG", new File(fileName));
}Capturing a single element is useful for debugging misaligned components or verifying specific UI states.
WebElement logo = driver.findElement(By.id("siteLogo"));
File elementShot = logo.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(elementShot, new File("logo.png"));With TestNG, screenshots can be triggered automatically when a test fails. This can be achieved through listeners (ITestListener) that hook into the test lifecycle.
public void onTestFailure(ITestResult result) {
File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(screenshot, new File("failure_" + result.getName() + ".png"));
} catch (IOException e) {
e.printStackTrace();
}
}By taking multiple screenshots, you can scrutinize the application behavior across various viewports.
According to a design practitioner survey, 84% of frontend teams have applied centralized design tokens. Because one token can break thousands of UI components, visual testing is the best way to spot and fix it.
Here is how you can take multiple screenshots and manage them during a test session:
String fileName = testName + "_" + System.currentTimeMillis() + ".png";/screenshots/checkout/paymentTest_1693647812.png
/screenshots/login/loginTest_1693647900.png /screenshots/failures / loginTest_Fail_1693647812.pngIf you are running tests in parallel using a worker instance, ensure you attach screenshots with the current test thread. Your script should contain a local class right within the main body of code.
It gives each thread it’s own WebDriver instance which stays local to that thread. So when threads run in parallel, screenshots are executed without any overlap.
This is critical since a screenshot taken on a wrong thread’s driver would capture the wrong browser session.
public class DriverManager {
private static ThreadLocal<WebDriver> driverThreadLocal = new ThreadLocal<>();
public static void setDriver() {
WebDriver driver = new ChromeDriver();
driverThreadLocal.set(driver);
}
public static WebDriver getDriver() {
return driverThreadLocal.get();
}
public static void unload() {
driverThreadLocal.remove();
}
} Each parallel thread calls DriverManager.getDriver() and gets back only its own driver instance, never another thread's.
The base class centralizes driver setup and teardown in one shared parent class, so every parent class inherits driver lifecycle management.
public class BaseTest {
protected WebDriver driver;
@BeforeMethod
public void setUp() {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://example.com");
}
@AfterMethod
public void tear Down() {
if (driver != null) {
driver.quit();
}
}
}Base class may save you from writing screenshot code, but it can also confuse testers by running multiple screenshots at the same time.
That’s why these two are mostly combined. The base class stores the driver as a ThreadLocal internally, giving both structure and consistency.
This example wires up three pieces: a base test class, a screenshot utility, and a listener that captures failures automatically.
public class BaseTest {
protected WebDriver driver;
@BeforeMethod
public void setUp() {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://example.com");
}
@AfterMethod
public void tearDown() {
if (driver != null) {
driver.quit();
}
}
}A utility class centralizes the logic for taking screenshots, making it reusable across tests.
public class ScreenshotUtil {
public static String captureScreenshot(WebDriver driver, String testName) {
String filePath = "screenshots/" + testName + "_" + System.currentTimeMillis() + ".png";
try {
File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(src, new File(filePath));
} catch (IOException e) {
e.printStackTrace();
}
return filePath;
}
}Listeners allow screenshots to be taken automatically when a test fails.
public class ScreenshotListener implements ITestListener {
@Override
public void onTestFailure(ITestResult result) {
WebDriver driver = ((BaseTest) result.getInstance()).driver;
String path = ScreenshotUtil.captureScreenshot(driver, result.getName());
System.out.println("Screenshot saved at: " + path);
}
}Register the listener in testng.xml:
<listeners>
<listener class-name="com.example.ScreenshotListener"/>
</listeners>Store screenshots in a clear hierarchy, with a separate folder per module or suite so it scales:
This produces clickable thumbnails in the TestNG HTML report, linking directly to the screenshot file.
Capturing screenshots is valuable, but you need to carefully manage your test scripts to ensure the process runs smoothly. When you push any new changes, take a screenshot to compare it with previous code.
Here are other best practices you can follow.
With Birds Capture by BrowserStack, you can record test runs, take session screenshots, and self-heal your code with AI self-healing agents. It lets everyone, including non-technical users, PMs, or clients, capture and report visual issues and go deeper into bug triage.
By integrating screenshot capture with BrowserStack’s real device cloud, teams ensure test reliability across real environments while benefiting from instant scalability and reduced maintenance overhead.
Taking screenshots in Selenium is an appropriate way to manage bug triage, follow compliance, and keep a trail of stack changes every time code changes are pushed.
You can either take a full-page screenshot or an element-specific screenshot, but the key is to cast WebDriver with TakesScreenshot and ensure no overlap happens.
When clubbed with products like Bird Capture By BrowserStack, you can not only take screenshots, but also get access to a detailed visual report to identify and solve visual bugs.
Get visual proof, steps to reproduce and technical logs with one click
Continue reading
Try Bird on your next bug - you’ll love it
“Game changer”
Julie, Head of QA
Try Bird later, from your desktop