Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

In Selenium 2 WebDriver, capture a screenshot by casting the driver to TakesScreenshot, calling getScreenshotAs(OutputType.FILE), and copying the temporary file to a predictable PNG path. Keep the call before driver.quit(), create the destination directory first, and use unique names when tests run repeatedly or in parallel.

Capture a Selenium 2 screenshot in Java

The WebDriver screenshot API is the TakesScreenshot interface. This complete helper creates the output directory, captures the current browser context, and copies the returned file to screenshots/<name>.png.

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;

public final class Screenshots {
    private Screenshots() {}

    public static void capture(WebDriver driver, String name) throws IOException {
        File directory = new File("screenshots");
        if (!directory.exists() && !directory.mkdirs()) {
            throw new IOException("Could not create " + directory.getAbsolutePath());
        }

        File source = ((TakesScreenshot) driver)
                .getScreenshotAs(OutputType.FILE);
        File target = new File(directory, name + ".png");
        FileUtils.copyFile(source, target);
    }
}

Apache Commons IO supplies FileUtils.copyFile; add the matching Commons IO dependency to the test project. The driver must implement TakesScreenshot. If it does not, the cast fails because that particular driver does not expose screenshot support.

Use the helper in a test

WebDriver driver = new ChromeDriver();
try {
    driver.get("https://example.com");
    Screenshots.capture(driver, "home-page");
} finally {
    driver.quit();
}

Capture after navigation, waits, and assertions have put the browser in the state you want to inspect. A screenshot taken immediately after get can show a loading state rather than the failed or completed UI.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Choose the output type: file or Base64

OutputType.FILE is convenient for attaching a PNG to a build artifact. Selenium also supports OutputType.BASE64, which is useful when a reporting system accepts an embedded image rather than a file.

String imageBase64 = ((TakesScreenshot) driver)
        .getScreenshotAs(OutputType.BASE64);
// Pass imageBase64 to a report that accepts Base64 image data.

Do not treat the temporary file returned by Selenium as a permanent artifact. Copy it to storage you control before the test process ends, and check that the copy succeeded.

Capture only an element

Driver screenshots and element screenshots are separate operations. Use the driver for the current browsing context; use a WebElement when the diagnostic image should contain one component such as a form, chart, or error panel.

WebElement errorPanel = driver.findElement(By.cssSelector(".error-panel"));
File source = errorPanel.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(source, new File("screenshots/error-panel.png"));

The element must implement the screenshot interface exposed by your binding and driver. Wait until it is present and rendered before capturing. An element image may contain only the visible portion when the driver cannot provide the element’s complete content.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Capture automatically when a test fails

A failure hook should run while the browser is still alive. Name files with the test class, method, and a collision-resistant suffix so parallel workers do not overwrite one another.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

TestNG example

import java.io.IOException;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;

public class CheckoutTest {
    private WebDriver driver;

    @AfterMethod
    public void saveFailureScreenshot(ITestResult result) throws IOException {
        if (result.getStatus() == ITestResult.FAILURE) {
            String testName = result.getTestClass().getName()
                    + "-" + result.getName()
                    + "-" + System.currentTimeMillis();
            Screenshots.capture(driver, testName);
        }
        if (driver != null) {
            driver.quit();
        }
    }
}

The important ordering is capture first, quit second. A listener can centralize the same logic for an entire suite. Selenide also documents JUnit and TestNG screen-shooter integrations; those are optional conveniences, not requirements for plain Selenium WebDriver.

JUnit integration pattern

With JUnit, put the capture in an @AfterEach or an extension that can determine whether the test failed. Preserve the thrown exception, capture before teardown, and then close the driver. If the test framework retries a method, include the retry number in the filename.

What Selenium 2 actually captures

Selenium 2 terminology includes both the old Selenium Remote Control commands and the newer WebDriver API. For WebDriver tests, TakesScreenshot.getScreenshotAs(OutputType<X>) is the relevant operation; legacy commands such as captureScreenshot and captureEntirePageScreenshot belong to a different API surface.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A screenshot is not automatically a full document image. For non-W3C-conformant drivers, Selenium describes a best-effort order: the entire page, the current window, the visible portion of the current frame, and finally the entire display. Element capture similarly prefers the whole element and then its visible portion. Browser, driver, Selenium binding, and version therefore matter. Document whether your artifact is a viewport/current-window image or a driver-supported full-page image.

Full-page expectations

  • Do not assume that a tall page is captured beyond the viewport.
  • Run the same browser and driver versions in CI and local reproduction when image dimensions matter.
  • For lazy-loaded content, scroll or otherwise trigger loading before capture if the page requires it.
  • Record the browser, driver, operating system, viewport, and Selenium binding alongside the image when diagnosing layout failures.

Reliable naming and storage

Use a stable directory layout such as screenshots/<class>/<method>-<timestamp>.png. Sanitize names supplied by parameterized tests so slashes and reserved characters cannot create unintended paths. For parallel execution, add a worker ID, UUID, or framework invocation number.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
  • Create directories before the copy operation and fail the test artifact step loudly if creation or copying fails.
  • Keep screenshots as build artifacts and attach them to the report rather than printing binary data to logs.
  • Use Base64 only when the report API needs inline data; file output is usually simpler and smaller to manage.
  • Capture the smallest useful scope for routine diagnostics, and reserve full-context captures for failures where surrounding layout matters.

Other Selenium bindings

The same WebDriver capability exists outside Java, but method names differ. The official Selenium examples use these patterns:

  • Python: driver.save_screenshot("screenshots/failure.png")
  • JavaScript: await driver.takeScreenshot(), which returns image data that you can write to a file.
  • Ruby: driver.save_screenshot("screenshots/failure.png")
  • .NET: ((ITakesScreenshot)driver).GetScreenshot().SaveAsFile(...)

Use the binding’s current method signature and preserve the same lifecycle rules: wait for the state, capture before teardown, and store a unique artifact.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Or skip the browser setup

If you only need a rendered image of a URL rather than a screenshot produced inside an existing Selenium session, ScreenshotNeo provides a single HTTP request. Its cleanup steps accept cookie or consent banners and remove more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and the response reports the page verdict and billing status in X-Page-Verdict and X-Billed headers.

See the ScreenshotNeo API documentation for all parameters. This call requests a WebP image:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Python equivalent:

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)

Node.js equivalent:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

ScreenshotNeo also offers an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. Options include full-page capture with lazy images loaded, CSS-selector element capture, dark mode, 12 device presets or custom viewports, retina scale, PDF paper settings and page ranges, custom CSS and JavaScript, pre-capture clicks, selector hiding, selector/delay/network-idle waits, request and resource blocking, custom headers, cookies, user agents and Authorization, timezone and geolocation, transparent backgrounds, resizing, configurable-TTL caching, signed image links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, a usage API, and an OpenAPI specification. Common parameter names from other screenshot APIs also work.

The Free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 shots; every feature is included on every plan, and yearly billing provides two months free. Sign up for the free ScreenshotNeo plan.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting

ClassCastException when casting the driver

The selected driver does not implement TakesScreenshot, or an incompatible driver object is being used. Use a WebDriver implementation with screenshot support and verify that the browser driver matches the browser and Selenium binding versions.

The file is missing or empty

Check that the destination directory exists, the process can write to it, and FileUtils.copyFile completed without an exception. In containerized CI, use an absolute artifact directory and confirm it is collected after the job.

The screenshot shows the wrong state

Capture after an explicit wait for the relevant selector, URL, or network-driven state. Assertions and screenshot calls that race application rendering can produce a valid image of an intermediate page.

Only the viewport appears

This is expected for drivers that do not provide full-page capture. Treat full-page output as driver-dependent, or capture the relevant element and document the resulting scope.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The failure hook throws after the test already failed

Make screenshot failure reporting non-destructive: log the capture error, preserve the original test failure, and always execute driver cleanup in a finally block. Never call quit before the hook.

Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Parallel tests overwrite each other

Add the class, method, parameter, retry, worker, and a timestamp or UUID to each filename. Avoid a single fixed name such as failure.png.

Implementation checklist

  1. Navigate and wait until the diagnostic state is visible.
  2. Cast the driver to TakesScreenshot and request OutputType.FILE (or BASE64 for an inline report).
  3. Create the destination directory and copy the returned file to a deterministic, unique PNG path.
  4. For element diagnostics, call the screenshot method on the target WebElement.
  5. Register the capture in a failure hook or listener and run it before driver.quit().
  6. Attach the artifact and record whether it represents a viewport, current window, frame, element, or driver-supported full page.

Frequently Asked Questions

Can Selenium 2 capture a screenshot after the browser is closed?

No. The driver must still be active when getScreenshotAs runs; capture first and call quit afterward.

Is a Selenium screenshot always PNG?

The Java file example writes a PNG path, while the driver controls the encoded screenshot returned. Treat the copied file according to the output produced by your driver and binding.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Should I use a driver screenshot or an element screenshot for a failed assertion?

Use a driver screenshot when surrounding page context matters and an element screenshot when the failing component is known and a smaller artifact is more useful.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.