ScreenshotNeo

BlogHow-to

Capture a Webpage Screenshot in Java with Selenium on an Indian Linux VPS

Capture a webpage with headless Chrome, save the screenshot from Java, and deploy Selenium reliably on an Indian Linux VPS.

By the ScreenshotNeo team4 October 20269 min read

Use Selenium’s Java TakesScreenshot API to capture the current browser viewport, then copy the resulting file to a path the service account can write. On a Linux VPS without a desktop, start Chrome with a supported headless option. Selenium Manager can resolve the driver when you have not supplied one yourself. The standard screenshot call captures the current browsing context; do not assume it captures the page’s entire scrollable height.

1. Check the VPS and browser prerequisites

This walkthrough applies to an Indian Linux VPS, but it does not assume a particular provider, city, operating-system image, or plan. Before choosing a host or deploying, check its current India-region availability, Linux distribution, browser package compatibility, outbound network access, and terms. Estimate CPU, memory, storage, and bandwidth from your own workload and intended concurrency; no universal resource minimum is established here.

  • Install a supported Java runtime and Selenium Java dependency in your application.
  • Install Chrome or Chrome for Testing on the VPS, along with the operating-system libraries it needs.
  • Make sure the account running Java can launch the browser and write to the screenshot destination.
  • Keep Chrome and ChromeDriver on matching major versions if you manage the driver yourself.
  • Retain startup logs so browser-launch and missing-library errors can be diagnosed from their actual messages.

Selenium Manager has been included with Selenium releases since 4.6. When no driver has otherwise been configured, Selenium bindings can use it as a fallback to manage the driver. Its binaries support Linux. It does not install the browser or guarantee that a particular VPS image includes every required shared library. See the official Selenium Manager documentation and ChromeDriver getting-started guide.

2. Add Selenium and capture the current page

Add the Selenium Java library using your build tool and use the following complete class. The Maven coordinates are shown here; use a Selenium version supported by your application and keep it updated according to your release process.

<dependency>
  <groupId>org.seleniumhq.selenium</groupId>
  <artifactId>selenium-java</artifactId>
  <version>4.27.0</version>
</dependency>

Save this as ScreenshotExample.java. It uses Java NIO to copy Selenium’s temporary screenshot file, so Apache Commons IO is not needed. Selenium Manager can provide the driver when no explicit driver path is configured.

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.time.Duration;

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

public class ScreenshotExample {
    public static void main(String[] args) throws Exception {
        String targetUrl = args.length > 0 ? args[0] : "https://example.com";
        Path output = Path.of(args.length > 1 ? args[1] : "./page.png")
                .toAbsolutePath();
        Path parent = output.getParent();
        if (parent != null) {
            Files.createDirectories(parent);
        }

        ChromeOptions options = new ChromeOptions();
        options.addArguments("--headless=new");
        options.addArguments("--window-size=1440,1000");

        WebDriver driver = new ChromeDriver(options);
        try {
            driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(60));
            driver.get(targetUrl);
            Path temporaryScreenshot = ((TakesScreenshot) driver)
                    .getScreenshotAs(OutputType.FILE).toPath();
            Files.copy(temporaryScreenshot, output,
                    StandardCopyOption.REPLACE_EXISTING);
            System.out.println("Saved screenshot to " + output);
        } finally {
            driver.quit();
        }
    }
}

--headless=new is documented by Selenium among common Chrome arguments. Confirm that the Chrome build installed on your server supports the argument. The explicit window size makes the viewport more predictable, but the resulting capture is still the current viewport. The Java example follows Selenium’s documented TakesScreenshot and OutputType.FILE flow; Selenium’s documentation also demonstrates copying the file with Apache Commons IO. See Selenium’s TakeScreenshot examples and Chrome-specific Selenium options.

Compile and run

For a Maven project, compile and run through your normal application packaging or exec setup. If you build a jar with dependencies, a typical invocation is:

java -jar target/screenshot-app.jar "https://example.com" "/var/tmp/page.png"

Use a destination owned by the service account, such as an application-specific directory. Avoid assuming the working directory is writable when the process runs under systemd, a container, or a dedicated account.

3. Choose what counts as ready to capture

driver.get() waits according to WebDriver’s page-load strategy, but a page can continue rendering after navigation returns. Decide what “ready” means for your target: a known element appearing, a fixed delay for a documented animation, or a page-specific condition. Do not add a long arbitrary sleep to every capture; it increases latency and can still miss delayed content.

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

new WebDriverWait(driver, Duration.ofSeconds(20))
        .until(ExpectedConditions.visibilityOfElementLocated(
                By.cssSelector("main")));

Place this wait after driver.get(targetUrl) and before the screenshot call. Replace main with a selector that signals readiness on the page you are capturing. If content is lazy-loaded below the fold, a viewport screenshot may not trigger it. Scroll and wait using page-specific logic only when that behavior is required, and verify the result; the basic Selenium screenshot example does not establish a full-page capture method.

4. Viewport, element, and full-page screenshots

Current viewport

The sample captures the current browsing context at the configured viewport dimensions. Set the window size before navigation when a consistent layout matters. Responsive sites can render different content at different sizes, so choose dimensions that match your intended output.

One element

Selenium’s Java API also supports capturing a web element. Locate the element after the page has reached the required state, then call getScreenshotAs on that element:

import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebElement;

WebElement card = driver.findElement(By.cssSelector("article.card"));
Path elementImage = card.getScreenshotAs(OutputType.FILE).toPath();
Files.copy(elementImage, Path.of("./card.png"),
        StandardCopyOption.REPLACE_EXISTING);

Element capture depends on the element being present and capturable in the current browser context. If it is below the fold or not yet rendered, wait for visibility and handle scrolling or page state explicitly. See the element example in Selenium’s screenshot documentation.

Entire scrollable page

Do not label the basic TakesScreenshot call as full-page capture. The cited Selenium example documents a current-context screenshot, not a guarantee that the entire scrollable document is included. Full-page techniques vary by browser and Selenium version; select and verify a method appropriate to your installed stack. If consistent full-page output is a requirement, test very tall pages, sticky headers, lazy-loaded images, and pages with dynamic content before deploying.

5. Deploy as a VPS service

  1. Run under the intended service user. Test browser launch and file writes as that same account, not only as an administrator.
  2. Check browser dependencies from actual errors. A missing shared library can prevent Chrome from starting. Install the library appropriate to the VPS distribution and the reported error; avoid copying an unrelated package list.
  3. Coordinate browser and driver updates. If supplying ChromeDriver directly, ensure its major version matches Chrome. With Selenium Manager, inspect logs when resolution fails and confirm the browser installation is discoverable.
  4. Set timeouts and cleanup. Bound navigation and readiness waits to your service’s request budget. Always quit the driver in a finally block so failures do not leave browser processes running.
  5. Control concurrency. Each active browser session consumes server resources. Measure your own workload and limit simultaneous sessions to what the selected VPS can sustain.
  6. Keep destinations and inputs controlled. Validate target URLs, restrict output paths to an application-owned directory, and apply your service’s network and access controls.

These are deployment practices, not claims about a tested Indian VPS provider or a fixed server size. The research for this guide did not verify provider pricing, city availability, resource minimums, or affiliate terms.

6. Common errors and fixes

Symptom Likely cause What to check
Session creation fails or ChromeDriver reports a version error Chrome and ChromeDriver major versions do not match, or the driver cannot be found. Record both versions. Align major versions or let Selenium Manager resolve the driver when no explicit driver is configured.
Browser exits immediately with a shared-library error A required operating-system library is absent from the VPS image. Use the exact missing-library name in the browser log to identify the distribution package. Selenium Manager’s docs show examples of this class of Linux error.
--headless=new is rejected The installed Chrome build does not support that argument. Check the installed browser version and use a headless argument supported by that version; Selenium documents headless options in its Chrome guidance.
Screenshot file is missing or copy fails The parent directory is absent, the process user lacks write permission, or the process uses a different working directory. Use an absolute application-owned destination, create parent directories, and test permissions as the service account.
Image is blank, incomplete, or shows a loading state Capture occurred before target content rendered, scripts failed, or the site returned a different response to the VPS. Wait for a meaningful page-specific selector; inspect the page and browser logs from the same server environment.
Only part of the page appears The code captured the viewport, not the full scrollable document. Use and verify a full-page method for the chosen browser and Selenium version, or capture a specific element.
Navigation hangs or times out The page is slow, unreachable from the VPS, or blocked by a network or site condition. Check outbound DNS and HTTPS connectivity, set a suitable page-load timeout, and distinguish navigation completion from application readiness.

7. Reliability, performance, and cost

Browser startup, navigation, and page rendering all contribute to capture time. Reusing a browser session may reduce repeated startup work, but it also requires careful isolation of cookies, storage, and state between targets. For isolated captures, create a session per job and always close it; for a service with reused sessions, define and enforce a cleanup and reset policy. Benchmark your own pages and concurrency on the chosen VPS rather than relying on a generic timing or memory estimate.

Retries can help with transient network failures, but retry only failures you have classified as transient and cap attempts. Repeating a permanently blocked URL or invalid browser setup adds load without fixing the cause. Preserve enough logs to distinguish driver startup, navigation, readiness, screenshot, and file-write failures.

VPS cost depends on the provider, India region, operating system, capacity, and usage. No provider or price was verified for this guide. Include the cost of operating and updating the browser stack, storage for retained images, and any outbound traffic in your own estimate.

8. Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server for developers. Instead of installing Java, Chrome, and a driver on your VPS, make one HTTP request; see the API documentation for the request options.

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 the capture; 60+ known consent platforms, newsletter popups, and chat widgets can be removed, with each step configurable.
  • Bot checks and CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed. Response headers report the page verdict and whether the request was billed.
  • An MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.
  • 1,000 screenshots per month are free with no card. Paid plans start at $5 for 3,000 screenshots; every feature is on every plan.

Create a free ScreenshotNeo account and get 1,000 screenshots a month with no card.

9. FAQ

Does this work on any Indian Linux VPS?

The Java and Selenium components support Linux, but a specific VPS image still needs a compatible browser, required libraries, network access, and writable output location. Verify those conditions on the host you select.

Do I need to download ChromeDriver manually?

Not necessarily. Selenium Manager can manage the driver as a fallback in Selenium 4.6 and later. If you provide a driver yourself, keep it compatible with the installed Chrome version.

Will the output be a PNG?

OutputType.FILE returns a screenshot file that the example copies to a .png destination, matching Selenium’s documented sample pattern. Keep the file extension consistent with the actual output format if your capture code changes.

Can I use this for a PDF?

This walkthrough covers image screenshots. Selenium’s screenshot API example does not make a PDF; PDF output is a separate browser or service workflow.