ScreenshotNeo

BlogHow-to

How to Capture the Visible Browser Area with Java

Capture exactly what Selenium’s browser viewport shows, save it in Java, troubleshoot common failures, and handle element or full-page screenshots.

By the ScreenshotNeo team1 October 20267 min read

Use Selenium’s TakesScreenshot interface on the active WebDriver. A driver screenshot captures the visual viewport of the top-level browsing context—the browser area currently visible to the user.

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

The result is a PNG image represented by Selenium as a File. Copy it to the destination you need. This is a viewport capture, not automatically a screenshot of the entire scrollable page.

1. What Selenium captures

The W3C WebDriver specification defines the Take Screenshot command as a capture of the top-level browsing context’s visual viewport. Selenium exposes that command through the Java TakesScreenshot interface. See the WebDriver specification and the Selenium Java API.

Target Use Java approach
Visible browser area Capture the current viewport ((TakesScreenshot) driver).getScreenshotAs(...)
One element Capture an element’s visible bounding rectangle element.getScreenshotAs(...)
Whole document Include content outside the viewport Use a document-area or browser-specific full-page method

An element screenshot scrolls the element into view before capturing its visible rectangle. Whole-document capture is a separate requirement; WebDriver BiDi distinguishes viewport and document screenshot areas in its browsingContext.captureScreenshot command. See MDN’s BiDi reference.

2. Complete Java example

This example assumes driver has already been created and navigated. It waits for the page to load, captures the visible area, and copies the temporary screenshot file to a stable path.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

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

            Path destination = Path.of("artifacts", "visible-area.png");
            Files.createDirectories(destination.getParent());

            Path temporaryFile = ((TakesScreenshot) driver)
                    .getScreenshotAs(OutputType.FILE)
                    .toPath();

            Files.copy(temporaryFile, destination,
                    StandardCopyOption.REPLACE_EXISTING);

            System.out.println("Saved screenshot to " + destination.toAbsolutePath());
        } finally {
            driver.quit();
        }
    }
}

Add Selenium’s Java client through your build tool, then provide the browser driver using your project’s normal WebDriver setup. The Selenium documentation includes a Java screenshot example in Working with windows and tabs.

Request Base64 instead of a file

Use OutputType.BASE64 when you need to send the image through JSON, store it in a database, or build a data URL.

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

Use OutputType.FILE for normal filesystem handling and OutputType.BYTES when your Selenium version exposes byte output and you want to write bytes directly.

3. Control the viewport before capturing

The screenshot follows the browser’s current window size, device scale, zoom, scroll position, and rendered state. Set these deliberately when repeatability matters.

import org.openqa.selenium.Dimension;

Dimension size = new Dimension(1440, 900);
driver.manage().window().setSize(size);
driver.get("https://example.com");

// Scroll position is part of what the viewport shows.
((org.openqa.selenium.JavascriptExecutor) driver)
        .executeScript("window.scrollTo(0, 0);");

File screenshot = ((TakesScreenshot) driver)
        .getScreenshotAs(OutputType.FILE);
  • Set the window size before navigation when responsive layouts matter.
  • Scroll to a known position before capture if the page should start at the top.
  • Wait for application content, fonts, images, and animations that must appear in the result.
  • Disable or finish animations when visual comparisons require stable pixels.

4. Capture one element

Use an element screenshot when the output should contain a component instead of the entire viewport.

import java.io.File;
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.WebElement;

WebElement chart = driver.findElement(By.cssSelector(".revenue-chart"));
File elementFile = chart.getScreenshotAs(OutputType.FILE);
Files.copy(elementFile.toPath(), Path.of("artifacts", "chart.png"),
        StandardCopyOption.REPLACE_EXISTING);

If the selector is missing, the element is hidden, or its layout changes between lookup and capture, Selenium can fail or return an unexpected region. Wait for visibility and locate the element immediately before taking the screenshot.

5. Viewport versus full-page screenshots

A driver screenshot does not promise the complete scrollable document. Content below the fold is outside the visual viewport. If you need the whole page, choose an explicitly supported document-area capture for your browser and Selenium version, or use a service that provides full-page capture. Do not label an ordinary viewport image as full page.

Full-page behavior can also be affected by sticky headers, lazy-loaded images, cross-origin frames, very tall documents, and browser-specific limits. Validate the exact browser and driver combination before relying on a document screenshot in production.

6. Timing and page state

Taking a screenshot immediately after get() can capture a loading shell. Use explicit waits for the condition that defines “ready” for your page.

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(20));
wait.until(ExpectedConditions.visibilityOfElementLocated(
        By.cssSelector("main")));

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

For dynamic pages, wait for a loading indicator to disappear, a key element to become visible, or a known application state. A fixed sleep can work for a quick script but is usually less reliable than a condition tied to the page.

7. Troubleshooting

Symptom Likely cause Fix
ClassCastException The driver implementation does not expose screenshot support. Use a Selenium browser driver that implements TakesScreenshot and cast the active driver, not a wrapper that hides the interface.
Screenshot is blank or mostly white Capture occurred before rendering, navigation failed, or the page is blocked. Check the current URL and page title, wait for a visible element, and inspect browser logs or the page source.
Output is the wrong size Window size, device scale, browser zoom, or headless defaults differ. Set the window dimensions explicitly and keep the same browser configuration in every environment.
Element screenshot throws an exception Element is absent, stale, hidden, or outside a usable layout. Wait for visibility, find the element again, and confirm it is rendered before capture.
Only the top portion of a long page appears Driver screenshot captures the viewport. Use a document-area or full-page method designed for your browser, or capture the required region separately.
Fonts or images are missing Web fonts and resources have not finished loading. Wait for the relevant element or application-ready state; ensure the test environment can reach those resources.
Intermittent differences between runs Animations, ads, time-dependent data, or responsive layout changes. Fix the viewport, wait for stable state, disable animation where appropriate, and control test data.

8. Performance, reliability, and cost considerations

  • Performance: The screenshot command is synchronous from the test’s point of view. The dominant time is usually navigation and rendering, so avoid repeated page loads when several viewport images can be taken from one prepared page.
  • Reliability: Save the file immediately, keep the browser lifecycle in a try/finally block, and record the URL, viewport size, browser, and timestamp alongside artifacts.
  • Parallel runs: Give each browser session its own output directory and avoid sharing mutable driver instances across threads.
  • Large pages: Viewport screenshots stay bounded by the window size. Full-document captures can consume substantially more memory and may hit browser-specific limits.
  • Cost: Selenium itself is browser automation running in your environment. Your total cost comes from compute, browser infrastructure, storage, and maintenance of drivers and page-wait logic.

9. Or skip the browser setup

ScreenshotNeo provides a website screenshot API when you want an image from a URL without maintaining Selenium and a browser session. Its options include viewport and device presets, custom dimensions, retina scale, full-page capture with lazy images loaded, element selection, waits, custom JavaScript and CSS, headers and cookies, blocking rules, caching, and PDF output. See the ScreenshotNeo API docs.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
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)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

Cookie and consent banners are accepted and removed before capture, along with more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits cost nothing, and the response reports the result in X-Page-Verdict and X-Billed headers. An MCP server lets Claude, Cursor, and other MCP clients call take_screenshot, get_page_info, and capture_pdf. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots.

Start with 1,000 free screenshots a month—no card required.

10. FAQ

Does Selenium capture the browser chrome?

No. The WebDriver screenshot is the webpage’s visual viewport, not the operating system window frame, address bar, or other browser chrome.

Can I capture a hidden element?

An element screenshot is intended for the element’s visible bounding rectangle after it is scrolled into view. Make the element rendered and visible before capture.

What image format does Selenium return?

The WebDriver protocol returns PNG image data. Selenium’s OutputType controls whether Java receives it as a file, Base64 string, or another supported representation.

Why is my screenshot not full page?

Because the ordinary driver command targets the visual viewport. Use a document-area or explicitly supported full-page capture when off-screen content is required.