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.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

To capture one element in Selenium Java, call getScreenshotAs on the WebElement, not on the driver. For a saved image, request OutputType.FILE and copy the temporary file to a path you control:

WebElement element = driver.findElement(By.cssSelector("h1"));
File temporaryScreenshot = element.getScreenshotAs(OutputType.FILE);
Files.copy(temporaryScreenshot.toPath(), Path.of("element.png"),
        StandardCopyOption.REPLACE_EXISTING);

This captures the element’s visible bounding region after Selenium scrolls it into view. It is not a full-page capture or a promise to include all content inside an element that has its own scroll area.

Capture and save a WebElement screenshot

Selenium’s Java WebElement interface supports getScreenshotAs because it extends TakesScreenshot. The API describes a screenshot-capable driver or HTML element as one that can capture a screenshot and store it in different ways. For the usual workflow—capture an element and leave an image file behind—use OutputType.FILE, then copy the returned temporary file to your chosen destination.

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

The following method assumes driver is already started and on the page to capture, and that the CSS selector identifies the intended element. It creates the destination directory if needed and replaces an existing file with the same name.

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

public static void saveElementScreenshot(WebDriver driver, Path destination)
        throws IOException {
    WebElement element = driver.findElement(By.cssSelector("h1"));
    File temporaryScreenshot = element.getScreenshotAs(OutputType.FILE);

    Path parent = destination.toAbsolutePath().getParent();
    if (parent != null) {
        Files.createDirectories(parent);
    }
    Files.copy(temporaryScreenshot.toPath(), destination,
            StandardCopyOption.REPLACE_EXISTING);
}

Call it after navigating to the target page, for example from a test or a helper that already has a configured driver:

saveElementScreenshot(driver, Path.of("screenshots", "page-heading.png"));

The method propagates IOException from directory creation or copying. Selenium capture problems are reported separately as WebDriver exceptions, so callers can distinguish a failed browser operation from a filesystem problem if they handle those exceptions at a higher level.

Choose an output type that fits the next step

The Java OutputType API offers three return forms. Use the form that matches what your code will do next rather than converting formats unnecessarily.

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.
Output type What you receive Best fit Important handling
OutputType.FILE A temporary File Saving an image to disk Copy it promptly to a durable destination. Selenium documents that the temporary file is deleted when the JVM exits.
OutputType.BYTES Raw screenshot bytes Passing the image to code that works in memory Write or process the bytes yourself if they need to persist.
OutputType.BASE64 Base64-encoded text An interface or transport that specifically expects encoded text It is text encoding of the screenshot, not a destination file; decode or pass it on as required by the receiving interface.

For example, the in-memory forms can be requested directly from the element:

byte[] pngBytes = element.getScreenshotAs(OutputType.BYTES);
String base64Image = element.getScreenshotAs(OutputType.BASE64);

Choose one call for the output you actually need. A file-based workflow should not rely on the temporary file surviving JVM shutdown, while a bytes-based workflow avoids creating that intermediate file.

What an element screenshot contains—and what it does not

The WebDriver specification defines an element screenshot as the visible region covered by the element’s bounding rectangle after the element has been scrolled into view. That makes it different from calling getScreenshotAs on the driver: a driver screenshot captures the current visual viewport, whereas the element call targets the element’s bounding region. The standard describes the capture region; it does not mean every browser and driver implementation will behave identically in every environment.

  • One element: call element.getScreenshotAs(...) when the desired image is the target element’s visible bounding area.
  • Current viewport: use the driver’s screenshot capability when the whole visible browser viewport is wanted.
  • Entire page: an element screenshot is not a general full-page capture. Full-page output requires a separate browser- or tool-specific capability.
  • Scrollable content inside the element: do not assume the capture expands to include all of an element’s internal scrollable contents. The defined target is the visible bounding rectangle.

These distinctions matter in visual tests: a screenshot can be valid but still show a different region from the one your test intended. Check the output against the element-versus-viewport requirement before treating it as a full-page artifact.

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

Make the capture reliable when the page changes

Element screenshots are sensitive to page state. A node can appear after navigation, move, or be replaced by a framework update. Locate it close to the capture rather than holding a reference across page changes.

  1. Navigate and wait for the target state. Wait for the content you intend to capture to finish rendering, especially if the target is inserted asynchronously. A fixed delay may be insufficient on a slow load and unnecessarily long on a fast one; prefer a condition tied to the page state you need.
  2. Find the element immediately before capture. Use a selector that identifies the intended node, such as By.cssSelector("h1"). If the page has updated since the element was found, find it again.
  3. Capture from the element. Use element.getScreenshotAs(OutputType.FILE) for the straightforward file workflow, or select bytes/base64 for an in-memory consumer.
  4. Persist or consume the result. Copy the temporary file to a named path, or pass the returned bytes or encoded text directly to the next operation.
  5. Keep browser lifecycle management separate. Close the driver in a finally block or in your test teardown, after screenshot work is complete. Do not leave a browser session open just to preserve the temporary screenshot file; copy the file instead.

Selenium checks that a referenced element is still fresh when its methods are called. If the page detached or replaced that node, the call may fail with StaleElementReferenceException. Re-find the element after the update rather than retrying the same stale reference.

Common failures and how to fix them

Symptom Likely cause What to do
NoSuchElementException while locating the target The selector does not match the current DOM, or capture began before the target appeared. Confirm the selector against the current page and wait for the target condition before calling findElement.
StaleElementReferenceException at capture time The stored element reference points to a node that was detached or replaced after it was found. Wait for the page update to finish, locate the element again, and capture using the fresh reference.
WebDriverException The screenshot operation failed, the session or browsing context is no longer usable, or the driver encountered another browser-side problem. Check that the browser session and current context remain open, verify that the element still exists, and inspect the driver’s underlying error message.
UnsupportedOperationException The implementation may not support the requested screenshot operation. Check the browser and driver combination and whether that driver supports element screenshots. Selenium documents best-effort behavior for non-W3C-conformant implementations.
The image disappears after the run The code kept only the temporary FILE rather than copying it to a durable path. Copy the file before JVM exit, or use BYTES and persist those bytes yourself.
The screenshot shows only part of what was expected The request was for an element bounding region, but the expected result was a viewport, full page, or all internal scroll content. Use the capture method that matches the required region; element capture is not a general full-page operation.

The screenshot API can throw WebDriverException when capture fails. Driver behavior can vary, so when a standards-based element call fails in one environment, investigate the browser, driver, session, and supported operation rather than assuming the Java call itself guarantees identical results everywhere.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If you need a screenshot of a page or a selected CSS element without configuring Selenium and a browser driver, ScreenshotNeo is a website screenshot API with a CSS-selector element capture option. Its single GET request can return an image or PDF. For instance, save a page screenshot like this; see the ScreenshotNeo API documentation for request options, including element capture.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

ScreenshotNeo removes cookie and consent banners, newsletter popups, and chat widgets before capture; those steps can be turned off. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers report the page verdict and billing status. Its MCP server provides 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 with no card; paid plans start at $5 for 3,000 screenshots. Every feature is available on every plan. Sign up for 1,000 free screenshots a month—no card required.

Which method should you use?

For an automated Java test that already controls a browser and needs exactly one DOM element’s rendered region, Selenium’s WebElement.getScreenshotAs is the direct choice. Select FILE when the test needs an image artifact, and copy that temporary file before the JVM exits. Choose BYTES or BASE64 when the next consumer expects in-memory data or encoded text. If the requirement is the full page rather than one element, choose a separate full-page capture approach instead of expecting this element method to expand its scope.

Frequently Asked Questions

Does Selenium save an element screenshot as a PNG?

The element screenshot operation returns the screenshot through the selected OutputType; Selenium’s standard screenshot mechanism produces PNG image data. Choose FILE, BYTES, or BASE64 based on how you need to handle that data.

Can I capture an element without saving a file?

Yes. Request OutputType.BYTES for a byte array or OutputType.BASE64 for encoded text instead of OutputType.FILE.

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

Can one WebElement screenshot capture a whole web page?

No. The standard element screenshot region is the element’s bounding rectangle after it is scrolled into view. Full-page capture is a separate capability.

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.