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

In Selenium 3.6 for Java, capture the current browser view by casting your WebDriver to TakesScreenshot and calling getScreenshotAs(OutputType.FILE). Copy the temporary file to a destination you control before quitting the driver. The same API can return bytes or a Base64 string when a file is not the right handoff.

What you need before capturing a screenshot

  • A Java project using Selenium 3.6.0 (the release includes TakesScreenshot and OutputType).
  • A browser driver that implements screenshot capture, such as a compatible ChromeDriver installation.
  • Write permission for the directory where the image will be saved.
  • If you use the sample exactly, Apache Commons IO for FileUtils.copyFile.

The screenshot call captures the current browsing context. It does not automatically mean a complete, stitched image of a page longer than the viewport. The captured extent can vary with the browser, driver and protocol implementation, so verify your particular combination before relying on full-page output.

Working Java example: save a PNG file

This is a complete Selenium 3.6-style program. It opens a page, captures the current view, copies the temporary result to screenshot.png, and always closes the browser.

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;
import org.openqa.selenium.chrome.ChromeDriver;

public class CaptureScreenshot {
    public static void main(String[] args) throws IOException {
        WebDriver driver = new ChromeDriver();
        try {
            driver.get("https://example.com");

            File temporaryScreenshot =
                ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

            FileUtils.copyFile(temporaryScreenshot, new File("screenshot.png"));
        } finally {
            driver.quit();
        }
    }
}

OutputType.FILE returns a temporary File. The copy operation creates the durable artifact; leaving the returned temporary file in place is not a reliable way to retain the image after the JVM exits.

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

How the code works

  1. new ChromeDriver() starts a browser session.
  2. driver.get(...) navigates to the target URL. Add any waits your page needs before capturing.
  3. The cast to TakesScreenshot exposes Selenium’s screenshot interface.
  4. getScreenshotAs(OutputType.FILE) asks the driver for a temporary image file.
  5. FileUtils.copyFile moves that image to the named destination.
  6. The finally block calls quit(), releasing the browser and driver even if navigation or saving fails.

Using a different output path

Pass an absolute or project-relative path to the destination file. Create the parent directory first when it may not exist, and ensure the Java process can write there. For example:

File destination = new File("artifacts/ui/homepage.png");
destination.getParentFile().mkdirs();
FileUtils.copyFile(temporaryScreenshot, destination);

Choose a unique name in parallel test runs so one browser does not overwrite another browser’s artifact.

Choose FILE, BYTES or BASE64

These values change the representation returned by Selenium, not the browser area being captured.

Output type Result Use it when Lifecycle note
OutputType.FILE Temporary File You want to copy an image to test artifacts or a durable folder Copy it before the process exits
OutputType.BYTES Raw screenshot bytes You will process, upload or attach the image in memory No intermediate file is required
OutputType.BASE64 Base64-encoded text The next system accepts an encoded image string Decode it or pass the string directly as required

Save bytes without a temporary file

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;

byte[] image = ((TakesScreenshot) driver)
    .getScreenshotAs(OutputType.BYTES);
Files.write(Path.of("screenshot.png"), image,
    StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);

If your Java level predates Path.of, use Paths.get instead. The Selenium 3.6 API supplies the bytes; the file-writing method is provided by Java.

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

Capture Base64 for an API payload

String encoded = ((TakesScreenshot) driver)
    .getScreenshotAs(OutputType.BASE64);

Do not write the Base64 text to a file named .png and expect an image viewer to open it. Decode it first, or send it to the service that expects Base64.

Timing, page state and screenshot scope

Wait for the state you intend to document

A screenshot reflects the browser at the instant the command runs. Navigate first, then wait for a specific element or application state rather than relying only on a fixed sleep. If images, fonts or client-side content are still loading, the saved artifact may be incomplete.

Current browsing context only

Switch into the intended window or frame before calling the method. The basic driver call concerns the current browsing context. Selenium’s interface can also describe a driver or HTML element that captures a screenshot, but support and extent depend on the implementation; do not assume Selenium 3.6 provides identical element or full-page behavior in every browser-driver pair.

Full-page expectations

A normal WebDriver screenshot is not a guaranteed page stitcher. If your requirement is a complete page, check the exact browser, driver and Selenium behavior you deploy, or use a capture service designed to load lazy images and produce full-page output. Treat any claim of universal full-page support as unsafe without a verified compatibility test.

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

Handle failures without losing the useful error

ClassCastException or unsupported capture

Not every driver implementation supports screenshots. A cast or capture can fail when the active driver does not implement the screenshot interface, and Selenium can report an unsupported operation through a WebDriverException. Use a supported browser-driver combination and check capability support before making screenshots a required test step.

WebDriverException during capture

The browser may have crashed, the session may have expired, or the driver may reject the operation. Record the exception, preserve browser and driver versions in your test log, and retry only when the failure is known to be transient. Retrying a broken session without creating a new driver generally cannot repair it.

File not found or access denied

The temporary file may exist while the destination directory does not, or the process account may lack write permission. Use an explicit destination, create its parent directory, and check destination.canWrite() or the equivalent deployment permissions. Copy the file before driver.quit().

Zero-byte, old or overwritten images

Give each run a unique destination name, close any stream that writes the bytes, and verify the resulting file size after the copy. In parallel execution, include a test name, timestamp or run identifier in the path.

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

Unexpected page content

Confirm that navigation completed, the correct window and frame are selected, and the expected element is visible. Replace arbitrary delays with an explicit wait for the state that matters to the test. A screenshot cannot correct a page that was captured before its UI reached the intended state.

Reliability and performance practices

  • Keep capture and copy inside the same try block so cleanup is deterministic.
  • Use BYTES when an uploader or assertion can consume memory directly; avoid unnecessary disk I/O.
  • Use FILE when CI systems collect files as artifacts, and copy immediately to the artifact directory.
  • Capture on failure as well as at checkpoints, but avoid taking images on every polling loop because image encoding and disk writes add overhead.
  • Use a naming convention that includes test and scenario identity; this prevents concurrent jobs from colliding.
  • Keep the browser and driver versions aligned with the Selenium 3.6 environment you actually support. The API documentation describes best-effort behavior for non-W3C-conformant drivers, so compatibility should be validated rather than assumed.

Or skip the browser setup

If you only need a URL screenshot rather than an interactive Selenium session, ScreenshotNeo provides a one-request website screenshot API. It can return PNG, JPEG or WebP, and its options cover full-page capture, a CSS-selected element, device and viewport settings, retina scale, waits, custom JavaScript or CSS, hidden selectors, cookies, headers, authentication, geolocation, timezone, blocking rules, resizing, caching and PDF output.

cURL:

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

Python:

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:

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

See the ScreenshotNeo documentation for parameters and response details. Before capture, it accepts cookie or consent banners and removes more than 60 known consent platforms, newsletter popups and chat widgets; each cleanup step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed as clean shots, and response headers identify the page verdict and billing status. ScreenshotNeo also offers an MCP server with take_screenshot, get_page_info and capture_pdf tools for Claude, Cursor and other MCP clients.

The Free plan includes 1,000 screenshots per month without a card. Paid plans start at $5 for 3,000 shots; yearly billing provides two months free, and every feature is included on every plan. Create a free ScreenshotNeo account.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

FAQ

Does OutputType.FILE create a permanent screenshot?

No. It returns a temporary file. Copy it to a destination you own if the image must survive JVM shutdown.

Can I use this API with Firefox or another browser?

Only when that browser’s driver implements screenshot capture. Selenium’s API defines the request, while the driver determines support and behavior.

What exception should my test catch?

Capture failures are reported through Selenium’s WebDriverException family; handle the error in a way that preserves the test failure and its diagnostic context.

Is a screenshot the same as a PDF or a full-page image?

No. The basic call captures a browser screenshot in the current context. PDF generation and guaranteed full-page rendering require separate, verified capabilities.

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

Frequently Asked Questions

Can I keep the temporary Selenium file after the test ends?

Treat it as disposable and copy it during the active WebDriver session.

Which output type is best for CI artifacts?

Use FILE and copy it to the CI artifact directory; use BYTES when the pipeline accepts image data directly.

Why does my screenshot show a loading page?

The capture ran before the target state was ready; wait for the relevant element or application condition first.

The Bottom Line

For Selenium 3.6, cast the driver to TakesScreenshot, call getScreenshotAs, and persist the result yourself. Select FILE, BYTES or BASE64 according to the next step, and verify browser-driver behavior before depending on full-page output.

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

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.