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

Call getScreenshotAs on the WebElement you want to save—not on the driver:

WebElement element = driver.findElement(By.cssSelector("h1"));
File screenshot = element.getScreenshotAs(OutputType.FILE);

Copy the returned temporary file to a durable path, or request bytes or Base64 text when your application needs an in-memory result. Selenium’s WebElement supports this because the interface extends TakesScreenshot. The element capture represents the visible region covered by the element’s bounding rectangle after Selenium scrolls it into view; it is not automatically a full-page capture.

Minimal Java example

The following method assumes that driver is already open on the target page and that the CSS selector identifies the element to capture.

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 final class ElementShots {
    private ElementShots() {}

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

A complete test normally creates the driver, navigates, waits for the page, calls the method, and closes the session in a finally block or test teardown. Keep the destination’s parent directory available and copy the file promptly: Selenium documents the FILE result as temporary and subject to deletion when the JVM exits.

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

What Selenium captures

The WebDriver specification defines an element screenshot as the region bounded by the element’s rectangle after it has been scrolled into view. A driver screenshot, by contrast, captures the current visual viewport. Consequently:

  • An element shot normally excludes unrelated page content.
  • It does not promise the element’s entire scrollable contents when the element itself has an internal scrollbar.
  • It is not a general full-page screenshot. Full-page support, if needed, is browser- or tool-specific and must be handled separately.

CSS effects, fonts, animations, overlays and lazy content are captured as rendered by the browser at that moment. If an animation changes the target while the command runs, wait for a stable state or disable the animation with test CSS.

Choose the output form

The Selenium OutputType API provides three useful forms.

Output Use it when What you must do
FILE You want a conventional image file. Copy the temporary file to a named, durable destination.
BYTES You will upload, compare or transform the image in memory. Write the returned byte array yourself if persistence is required.
BASE64 An API, report or message accepts encoded text. Transmit the returned string; decode it before writing a binary file.

Save bytes directly

byte[] png = element.getScreenshotAs(OutputType.BYTES);
Files.write(Path.of("artifacts/header.png"), png);

Return Base64

String encoded = element.getScreenshotAs(OutputType.BASE64);
// Send encoded to a system that explicitly expects Base64 text.

The default image format is controlled by the driver implementation. Treat the returned data as the format advertised by your browser/driver rather than renaming it blindly.

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

Reliable capture sequence

  1. Navigate. Call driver.get(url) and select the intended window or tab.
  2. Wait for the real content. For an element inserted or replaced by JavaScript, wait for its presence and, when necessary, visibility or a page-specific readiness condition.
  3. Locate immediately before capture. A previously stored reference can become invalid if the DOM replaces the node.
  4. Capture on the element. Use element.getScreenshotAs(...), not driver.getScreenshotAs(...), when only the element is wanted.
  5. Persist or process the result. Copy FILE, write BYTES, or transmit BASE64.
  6. Close the browser separately. Put driver.quit() in teardown or a finally block so a failed capture does not leak sessions.

Waiting with an explicit condition

import java.time.Duration;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(15));
WebElement card = wait.until(ExpectedConditions.visibilityOfElementLocated(
        By.cssSelector("article.product-card")));
File tmp = card.getScreenshotAs(OutputType.FILE);
Files.copy(tmp.toPath(), Path.of("artifacts/product-card.png"),
        StandardCopyOption.REPLACE_EXISTING);

Visibility means Selenium can see the element; it does not guarantee that images, fonts or application data have finished loading. Add an application-specific condition, wait for a selector that marks readiness, or use a short deliberate delay only when there is no better signal.

Selectors and page state

Prefer stable selectors

Use an ID, a dedicated data-testid, or a semantic CSS class that your application treats as stable. Avoid selectors tied to generated class names or changing list positions. XPath is also valid:

WebElement logo = driver.findElement(By.xpath("//header//img[@alt='Company logo']"));

Frames, windows and shadow DOM

If the target is inside an iframe, switch to that frame before locating it; switch back afterward if later commands address the parent document. For another tab or window, switch to its handle before finding the element. Shadow DOM requires the appropriate shadow-root API and a selector inside that root. The screenshot call must run in the browsing context that owns the element.

Scroll position and fixed overlays

Selenium scrolls the target into view as part of element capture. A sticky header, cookie notice or modal can still cover pixels in the rendered result. Dismiss or hide the overlay before locating the target, and verify the captured rectangle in your test artifacts.

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

Common failures and fixes

Symptom or exception Likely cause Fix
NoSuchElementException The selector is wrong or the element has not been inserted. Check the selector in browser developer tools, select the correct frame/window, and wait for presence.
StaleElementReferenceException The page detached or replaced the node after you found it. Wait for the update to finish and find the element again immediately before getScreenshotAs.
ElementNotInteractableException or an empty-looking image The element is hidden, outside the rendered state, covered, or not yet populated. Wait for visibility and application readiness; remove overlays; confirm that the selector identifies the visible instance.
WebDriverException The browser session, current browsing context, or screenshot command failed. Check that the driver is still open, the window handle is valid, and browser and driver versions are compatible; capture diagnostic logs.
UnsupportedOperationException The implementation does not support the requested screenshot operation. Use a conforming, current WebDriver implementation or a browser-specific supported path. Selenium describes some non-conformant behavior as best effort.
The file disappears later OutputType.FILE returned a temporary file. Copy it immediately to durable storage, or use BYTES and write the bytes yourself.

The official WebElement API and TakesScreenshot API document the relevant contracts. Selenium also includes driver- and element-screenshot examples in its windows and tabs documentation.

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

Performance, reliability and test design

  • Capture only what you assert. Element images are generally smaller and easier to review than viewport or page images.
  • Avoid unnecessary repeats. Each capture involves browser and filesystem or memory work; take one artifact per failure or checkpoint unless visual history is the requirement.
  • Use deterministic rendering. Fix viewport, device scale, locale, timezone and test data where visual comparisons matter. Disable blinking cursors and transitions with test-only CSS.
  • Keep artifacts identifiable. Include test name, browser, build and a unique timestamp or run ID in the destination path.
  • Protect sensitive data. Screenshots can contain tokens, personal information and internal URLs. Restrict artifact access and delete them according to your retention policy.
  • Do not infer browser performance. Selenium’s APIs do not establish a universal browser-by-browser speed or image-quality ranking for element screenshots.

Element screenshots versus page screenshots

Need Use Result
One card, button, chart or heading WebElement.getScreenshotAs The element’s visible bounding region.
Everything currently visible WebDriver.getScreenshotAs The visual viewport.
A complete long page A full-page capability supported by your chosen browser or service Implementation-specific; not provided by the element contract.

Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server. One GET request returns PNG, JPEG, WebP or PDF, and its element capture can target a CSS selector without maintaining a Selenium session. Before capture it accepts cookie and consent banners and removes more than 60 known consent platforms, newsletter popups and chat widgets; each cleanup step can be disabled. Bot checks, 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. Its MCP tools—take_screenshot, get_page_info and capture_pdf—work with Claude, Cursor and other MCP clients.

Java is not required for the API call. See the ScreenshotNeo documentation for all parameters, including CSS selectors, waits, custom JavaScript and CSS, device presets, viewport and retina scale, PDF settings, headers, cookies, user agents, authorization, timezone, geolocation, blocking rules, transparent backgrounds, resizing, caching, signed links, asynchronous webhooks, bulk capture and usage reporting.

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)
r.raise_for_status()
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}`);
if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
require('fs').writeFileSync('shot.webp', Buffer.from(await res.arrayBuffer()));

The Free plan includes 1,000 shots each month without a card. Paid plans start at $5 for 3,000 shots; yearly billing gives two months free, and every feature is available on every plan. Sign up for the free 1,000-shot plan.

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

Frequently Asked Questions

Can I capture an element that is not currently visible?

Selenium scrolls the element into view for the element screenshot command, but hidden elements have no visible rendered region. Make the intended instance visible first and account for sticky overlays.

Does an element screenshot include a scrollable div’s entire contents?

No. The WebDriver element screenshot covers the visible bounding region after scrolling the element into view, not automatically every pixel in an element’s internal scroll area.

Should I keep the WebElement reference between page updates?

Usually not. If JavaScript replaces the node, the old reference becomes stale; wait for the update and locate the element again immediately before capture.

The Bottom Line

For Selenium Java, locate the target, call element.getScreenshotAs(OutputType.FILE), and copy the temporary result immediately. Use BYTES or BASE64 for in-memory workflows, and choose a separate full-page capability when an element bounding region is not enough.

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.