Contents

    Guides

    Screenshots in Selenium: Complete Guide

    Published on

    September 10, 2025
    Screenshots in Selenium: Complete Guide

    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

    Why Screenshots Matter in Selenium Automation?

    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.

    • Separating real bugs from flaky tests: An app can be broken for various reasons. It can be stale locator or timing issues. Screenshots only depict real UI failures (like a broken button or missing form) and don't capture flaky tests to save time.
    • Making reports meaningful to non-engineers: Non-engineers can use screenshots to trace the stack and evaluate errors. A screenshot showing exactly what is rendered helps understand the issue and take immediate QA measures for it.
    • Providing an audit trail for compliance: Having a visual trail or evidence of Selenium code also simplifies audit handling. Testers can view the document to spot the bugs, which increases transparency with the rest of the stakeholders.
    • Speeding up cross-browser and cross-device checks: Many rendering issues are visual rather than functional. Screenshots taken across real devices are browsers testify that the app behaves consistently and eliminates discrepancies. 

    Screenshots in Selenium help diagnose test failures, provide visual evidence for bug reporting, and ensure UI consistency across browsers.

    Example of Screenshots in Selenium

    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. 

    example of screenshots in selenium

    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:

    1. The driver (your WebDriver instance) is cast to the TakesScreenshot interface.
    2. .getScreenshotAs(OutputType.FILE) captures the current browser view and returns it as a temporary file.
    3. FileUtils.copyFile() (from Apache Commons IO) copies that temporary file to a permanent location. In this case, screenshot.png.

    How to Capture a Screenshot on Failure in Selenium

    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.

    How to Take Screenshots in Java

    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. 

    • OutputType. FILE: Returns a temporary file on disk (most common, used when saving to a permanent location.)
    • OutputType. BASE64: Returns a Base64-encoded string (useful for embedding in HTML reports or sending over an API)
    • OutputType. BYTES: Returns a raw byte array (useful for in-memory processing without touching the file system)
    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. 

    failure triggered screenshot flow.

    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

    Environment Setup for Enabling Screenshots

    Before capturing screenshots, make sure that the environment is correctly configured. The essential step includes.

    • Java Development Kit (JDK): Ensure JDK is installed and configured in the system PATH.
    • Maven or Gradle: Recommended for managing Selenium dependencies.
    • Selenium WebDriver: Add the Selenium Java dependency to your project.
    • TestNG (or JUnit): Provides structured test execution and reporting.
    • Browser drivers: ChromeDriver, GeckoDriver, or others must be installed and linked.

    Sample Maven dependency for Selenium:

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>4.12.0</version>
    </dependency> 

    How does “TakesScreenshot” help Capture Screenshots with Selenium WebDriver?

    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:

    • Full Page Screenshot: Captures the whole browser window or the visible viewport of the browser
    • Web element screenshot: Captures elements like buttons, input text, form fields, or error messages.
    • On-demand screenshot: Allows testers to take a screenshot right after a regression test run. 
    • Failure-triggered screenshot: If the test run fails, Selenium WebDriver takes a screenshot of the code.

    There are various methods that you can use with TakesScreenshot to manage the image file: 

    • getScreenshotAs(): Selenium's built-in method that captures the browser snapshot and saves it internally as a file, Base64 string, or byte array.
    • ScreenshotUtil: A custom utility class that wraps getScreenshotAs() into one reusable method, so tests don't repeat the same capture-and-save logic.

    How to Take Screenshots in C#

    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);
    • It takes a screenshot cast to the driver instance from the interface before capturing.
    • GetScreenshot() returns a Screenshot object, which wraps the image data.
    • SaveAsFile() writes it to disk directly. No separate file-copy step is needed like in Java's FileUtils.copyFile().

    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. 

    How to Take Screenshots in Python

    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.

    How to Take a Full-Page Screenshot in Selenium

    Selenium’s default capability captures only the visible viewport. For full-page screenshots:

    • Use WebDriver extensions like AShot.
    • Browser-specific options (e.g., Chrome DevTools protocol in Selenium 4).

    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));
    }

    Element-Specific Screenshot Capture

    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"));

    Generating Screenshots on Test Failures

    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();
        }
    }

    Managing Multiple Screenshots During a Test Session

    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: 

    • Use unique file names. When taking multiple screenshots in Selenium WebDriver using Java, append the test name and timestamp so files never collide.
     String fileName = testName + "_" + System.currentTimeMillis() + ".png";
    • Organize into hierarchical folders, by module or suite, instead of one flat directory:
    /screenshots/checkout/paymentTest_1693647812.png
    /screenshots/login/loginTest_1693647900.png 
    • Separate failures into routine checkpoints: Separate flaky tests from routine checkpoints so that the images do not get buried with other files. 
    /screenshots/failures / loginTest_Fail_1693647812.png
    • Clean up old screenshots periodically in CI so disk usage doesn't grow unbounded.
    • Hook screenshots automatically into your reporting tool to have all the bug reports in a centralized place.

    Handling WebDriver in Parallel Tests (ThreadLocal / Base Class)

    If 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.

    ThreadLocal WebDriver

    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.

    Base Class Approach

    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.

    End-to-End Example: Implementing Screenshots in Selenium

    This example wires up three pieces: a base test class, a screenshot utility, and a listener that captures failures automatically.

    1. Base Class: Manage the WebDriver

    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();
            }
        }
    }

    2. Utility: Capture and Save Screenshots

    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;
        }
    }

    3. Listener: screenshot on failure

    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>

    4. Organize the Output

    Store screenshots in a clear hierarchy, with a separate folder per module or suite so it scales:

    • /screenshots/moduleName/testName_timestamp.png‍
    • Separate directories per test suite or module for scalability.

    This produces clickable thumbnails in the TestNG HTML report, linking directly to the screenshot file.

    Best Practices for Screenshot Management

    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.

    • Use standardized naming conventions: Include test name, status, and timestamp: LoginTest_Fail_1693647812.jpg. This tells you what exact step the screenshot was taken.  ‍
    • Capture selectively: Don’t screenshot every step. Focus only on taking a screenshot if you notice a UI inconsistency. Excessive screenshots bloat test runs.‍
    • Use lightweight formats: Stick to PNG or JPEG; avoid BMP or other uncompressed formats that produce unnecessarily large files.‍
    • Set a retention policy. Auto-delete older screenshots or builds older than a set number of days, so storage doesn't interrupt with the CI server.‍
    • Integrate with CI/CD. Publish screenshots as builds in Jenkins, GitHub Actions, or similar, so failures are debuggable directly from the build and you get a visual trail.

    How Does Birds Capture By BrowserStack Help You Capture Screenshots?

    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.

    • One-click capture. Clicking "Take a screenshot" captures the current tab, and immediately after, you can annotate it via a toolbar. ‍
    • Screenshots with technical context attached. If Replays is enabled, captured screenshots automatically include technical logs from the last 2 minutes. A screenshot isn't just an image; it comes bundled with the browser state leading up to it. ‍
    • Annotation built in. After capturing, testers can mark up the screenshot directly, circling the broken element and adding notes, before it's ever sent to a developer.‍
    • No technical skill required. It's designed to let anyone, regardless of technical ability, report bugs clearly so engineers can debug more effectively.‍
    • Two ways to embed it. A browser extension works as a self-serve recorder for individual testers, while a Web SDK widget can be embedded directly into a webpage with a single line of code to help report bugs across real devices and platforms.

    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.

    Conclusion

    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.

    Data-rich bug reports loved by everyone

    Get visual proof, steps to reproduce and technical logs with one click

    Make bug reporting 50% faster and 100% less painful

    Rating LogosStars
    4.6
    |
    Category leader

    Liked the article? Spread the word

    Put your knowledge to practice

    Try Bird on your next bug - you’ll love it

    “Game changer”

    Julie, Head of QA

    star-ratingstar-ratingstar-ratingstar-ratingstar-rating

    Overall rating: 4.7/5

    Try Bird later, from your desktop