ScreenshotNeo

BlogHow-to

How to Capture a Webpage Screenshot with Selenium Grid in Java

Capture a browser screenshot through Selenium Grid in Java. Set up RemoteWebDriver, save the image safely, and troubleshoot common Grid issues.

By the ScreenshotNeo team4 October 20268 min read

To capture a webpage screenshot with Selenium Grid in Java, create a RemoteWebDriver using the Grid URL and browser options, navigate to the page, and call getScreenshotAs through Selenium’s TakesScreenshot interface. Save the returned image before the Java process exits: OutputType.FILE is temporary.

The standard WebDriver screenshot represents the current browsing context. It should not be assumed to capture the entire document from top to bottom. For an element screenshot or full-page capture, use the appropriate element or browser-specific approach.

1. Start Selenium Grid and add the Java dependencies

For a local setup, Selenium’s getting-started guide describes starting the server in Standalone mode. With the server running, the default endpoint is http://localhost:4444. For a remote or containerized Grid, use an endpoint reachable from the Java test process; localhost may refer to the client machine rather than a Grid container.

java -jar selenium-server-<version>.jar standalone

Use Java 11 or later, and have the browser available to the Selenium server. Add Selenium Java and Apache Commons IO to your project. For Maven, put the versions that match your project’s dependency policy in the properties below:

<properties>
  <selenium.version>YOUR_SELENIUM_VERSION</selenium.version>
  <commons-io.version>YOUR_COMMONS_IO_VERSION</commons-io.version>
</properties>

<dependencies>
  <dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>${selenium.version}</version>
  </dependency>
  <dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>${commons-io.version}</version>
  </dependency>
</dependencies>

In a multi-node Grid, the same Java client pattern applies. Grid routes WebDriver commands to a browser running on a remote machine, so the client must be able to reach the Grid endpoint and the Grid must be configured with a compatible browser.

2. Capture and save the screenshot in Java

This complete example creates a Chrome session, opens a URL, captures the current browsing context, copies the temporary screenshot to screenshot.png on the Java client’s filesystem, and releases the session even if an operation fails.

import java.io.File;
import java.io.IOException;
import java.net.URL;

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.ChromeOptions;
import org.openqa.selenium.remote.RemoteWebDriver;

public class GridScreenshot {
  public static void main(String[] args) throws IOException {
    URL gridUrl = new URL("http://localhost:4444");
    ChromeOptions options = new ChromeOptions();
    WebDriver driver = new RemoteWebDriver(gridUrl, options);

    try {
      driver.get("https://example.com");
      File temporaryScreenshot = ((TakesScreenshot) driver)
          .getScreenshotAs(OutputType.FILE);
      FileUtils.copyFile(temporaryScreenshot, new File("screenshot.png"));
    } finally {
      driver.quit();
    }
  }
}

Replace the Grid URL with the address visible to the Java client and replace the target page URL with the page you want to capture. The screenshot file is written relative to the process’s working directory. Choose an absolute path if your build or job runner uses a different working directory.

Run it with Maven

Save the class under src/main/java/GridScreenshot.java and use the Maven Exec Plugin (configured in your project) or run it from your IDE. The snippet demonstrates the documented Selenium calls; dependency and plugin versions should be selected for your project.

Choose the screenshot output type

Output type What you receive When to use it
OutputType.FILE A temporary image file Copy it to a durable path before the JVM exits.
OutputType.BYTES Raw image bytes Pass the bytes to your existing storage or processing code.
OutputType.BASE64 Base64-encoded image data Use when the next step in your pipeline expects encoded data.

For example, writing bytes directly avoids handling Selenium’s temporary file:

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

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

The output type changes how the image data reaches your Java code, not the screenshot’s scope. The standard operation is for the current browsing context.

3. Configure browser options and understand capture scope

Pass browser-specific options to RemoteWebDriver so the Grid can select and start the intended browser. The example uses ChromeOptions; use the options class for the browser configured on your Grid. The Grid URL and options are both part of creating the remote session.

Before capturing, navigate to the target page and wait for the page state your application requires. A successful navigation call does not by itself mean that asynchronous content, fonts, or images have finished loading. Add an explicit wait for a known page condition when the screenshot depends on it. Avoid arbitrary long delays when a specific readiness condition is available.

  • Current browsing context: driver.getScreenshotAs(...) captures the active browser context. Do not describe this generic call as a reliable full-document capture.
  • One element: Selenium exposes a separate screenshot operation on a WebElement. Locate the element and use its screenshot method when only that element is needed.
  • Full page: Full-page behavior depends on browser and API support. Verify the specific browser and method you intend to use; it is not implied by the generic TakesScreenshot call.

For a layout-dependent screenshot, set the browser window size through the relevant browser options or driver window management before capture. Keep that viewport consistent across runs if you are comparing screenshots. The dossier does not establish a universal Grid setting for full-page capture or a cross-browser full-page API.

4. Save the artifact where your pipeline can retrieve it

The Java client copies the temporary screenshot to its own filesystem. It is not a download placed in the browser node’s downloads folder. In CI, write to the artifact directory expected by the runner, then configure that runner to retain or publish the file.

If downstream code consumes the image in memory, use BYTES or BASE64 instead of a temporary file. If you use FILE, copy it while the JVM is still running. Use a unique destination filename for parallel jobs so simultaneous captures do not overwrite each other.

5. Troubleshoot common failures

Symptom Likely cause Fix
Connection refused or session creation fails The Grid is not running, or the endpoint is wrong or unreachable from the Java client. Check that the server is running and set the URL to the Grid address reachable from the test process. For containers, do not assume the client’s localhost is the Grid host.
No matching browser or session cannot start The requested browser options do not match a browser available on the Grid. Use the options for a browser configured on the Grid and check that the browser is available to the server.
Screenshot file disappears The code kept only Selenium’s temporary OutputType.FILE result. Copy it to a durable destination before JVM exit, or write BYTES to the destination directly.
File is not in the expected directory The relative path is resolved from the Java process’s working directory, or the code expects a browser-node file. Use an explicit client-side path and have the CI runner collect that path as an artifact.
Screenshot is blank or misses late content The page had not reached the state required by the capture when the screenshot was requested. Wait for a meaningful page condition, such as a target element becoming visible, before capturing.
Screenshot omits lower page content The generic screenshot call captures the current browsing context rather than promising a full-page image. Use a verified browser-specific full-page method if full-document capture is required.
Grid sessions accumulate after failures The session was not closed when navigation or file handling threw an exception. Put driver.quit() in a finally block, as in the example.

6. Performance, reliability, and cost considerations

A Grid screenshot requires remote browser work and a result transfer back to the Java client. Keep the page and capture scope focused on what the test needs, avoid unnecessary sessions, and always close each session. For parallel capture, make output paths unique per test and size Grid capacity for the number of sessions your workload requests. The research basis provides no benchmark or universal timing figure, so measure the pages and Grid configuration that matter to your pipeline.

For reliable visual comparisons, control the browser, viewport, page readiness condition, and test data. A capture taken before dynamic content stabilizes can differ even when the screenshot code is correct. Persist artifacts from the client side and retain enough context in the test output to identify the URL and failed step.

Selenium Grid is self-hosted software infrastructure in this workflow; the dossier does not establish a per-screenshot Selenium price. Account for the machines and operational work used to run the Grid, as well as the time needed to maintain browser availability and artifact storage.

7. Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server from Yorker Media. One GET request returns an image or PDF. Its API accepts familiar screenshot parameter names, which can make switching from another screenshot API easier. See the ScreenshotNeo API documentation.

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

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://example.com"},
    timeout=90,
)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://example.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot request failed: ${res.status}`);
await Bun.write('shot.webp', res);

In Node.js environments without Bun, save the response body using the file APIs available in your project. The request itself uses the documented ScreenshotNeo endpoint and query parameters.

  • Cookie and consent banners are accepted and removed before capture; more than 60 known consent platforms, newsletter popups, and chat widgets can be removed, and each step can be turned off.
  • Bot checks, blank pages, timeouts, failed loads, and cache hits cost nothing. Responses include X-Page-Verdict and X-Billed headers.
  • An 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 ScreenshotNeo’s free plan to get 1,000 screenshots a month with no card.

8. FAQ

Does the Java client need to run on the Grid machine?

No. Grid routes WebDriver commands to a remote browser, so the client needs a Grid URL reachable from where the Java process runs.

Can I return the screenshot without creating a file?

Yes. Request OutputType.BYTES or OutputType.BASE64 and pass that result to the next step in your pipeline.

Does the standard call capture the entire webpage?

Do not rely on that assumption. It captures the current browsing context; full-page capture requires a browser-specific method verified for your setup.