ScreenshotNeo

BlogHow-to

Java Selenium Full-Page Screenshots for Indian Ecommerce Websites

Capture beyond the viewport with Chrome DevTools Protocol in Java, save a PNG, and validate dynamic Indian ecommerce pages and browser versions.

By the ScreenshotNeo team4 October 20269 min read

To capture a full-page screenshot with Selenium in Java, use Chrome’s DevTools Protocol (CDP) Page.captureScreenshot command with captureBeyondViewport enabled. Selenium’s standard WebDriver screenshot API captures the current browsing context, but does not promise a full-document image. The CDP route is Chrome-specific, and its Java bindings vary by Selenium version. Validate the code against your Selenium, Chrome, ChromeDriver, and target page.

This is useful for Indian ecommerce test targets when you need to inspect the whole rendered page, including below-the-fold product listings. The sources used here do not establish behavior for any named retailer, so treat localization, page structure, anti-automation behavior, and dynamic content as things to verify in your own authorized test environment.

How do I take a full-page screenshot with Selenium in Java?

  1. Use a Selenium Java dependency that includes the Chrome DevTools binding for the CDP version supported by your Chrome session.
  2. Start Chrome and navigate to the target URL.
  3. Wait for the page content you need, including relevant lazy-loaded images and dynamic sections.
  4. Measure the document dimensions, then call Page.captureScreenshot with captureBeyondViewport enabled.
  5. Decode the returned Base64 data and write the image bytes to a file.
  6. Open the saved file and check the bottom of the page, images, sticky elements, overlays, and locale-specific content.

The example below follows the Selenium 4.22.0 DevTools v124 Java API signature. It is version-specific sample code, not a promise that the same imports or method signature work unchanged with every Selenium or Chrome release.

Java example with Chrome DevTools Protocol

Use a Selenium Java dependency and a matching DevTools artifact for the CDP version available in your Selenium distribution. The imports below show the v124 binding; adjust the versioned package and method signature when your dependency uses a different CDP version. Selenium’s documentation says Selenium 4 is compatible with Chrome 75 and newer and advises matching the Chrome and ChromeDriver major versions.

import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.Base64;
import java.util.Optional;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.v124.page.Page;

public class FullPageScreenshot {
    public static void main(String[] args) throws Exception {
        String targetUrl = "https://example.com"; // Replace with an authorized test URL.
        Path output = Path.of("full-page.png");

        WebDriver driver = new ChromeDriver();
        try {
            driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(60));
            driver.manage().window().setSize(new org.openqa.selenium.Dimension(1440, 1000));
            driver.get(targetUrl);

            WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(30));
            // Replace this with a selector that identifies the content your test needs.
            wait.until(ExpectedConditions.presenceOfElementLocated(By.tagName("body")));

            // Optional: wait for a known product/listing selector instead of relying
            // only on the body or page-load event.
            // wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".product-grid")));

            JavascriptExecutor js = (JavascriptExecutor) driver;
            Number width = (Number) js.executeScript(
                "return Math.max(document.documentElement.scrollWidth, document.body.scrollWidth);"
            );
            Number height = (Number) js.executeScript(
                "return Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);"
            );

            DevTools devTools = ((ChromeDriver) driver).getDevTools();
            devTools.createSession();
            devTools.send(Page.enable());

            // Selenium 4.22.0 / DevTools v124 API form. The final optional argument
            // enables capture beyond the viewport. Check your binding's signature.
            String base64 = devTools.send(Page.captureScreenshot(
                Optional.of(Page.CaptureScreenshotFormat.PNG),
                Optional.empty(), // quality: used for JPEG where supported
                Optional.empty(), // clip: capture the full page rather than a clip
                Optional.of(true),
                Optional.of(true), // captureBeyondViewport
                Optional.empty()  // optimizeForSpeed
            ));

            Files.write(output, Base64.getDecoder().decode(base64));
            System.out.printf("Saved %s (document approximately %s × %s CSS pixels)%n",
                output.toAbsolutePath(), width, height);
        } finally {
            driver.quit();
        }
    }
}

The dimensions are measured for inspection and logging; the CDP command’s beyond-viewport option is the key setting. The exact v124 binding may represent optional parameters differently depending on the generated API. Consult the API for the CDP artifact in your project before compiling.

Version and setup checklist

  • Chrome and ChromeDriver: use the same major version, as Selenium’s Chrome guidance recommends. Confirm the actual browser and driver versions used in CI as well as locally.
  • Selenium and CDP binding: use the DevTools Page API shipped for the Chrome DevTools Protocol version supported by your Selenium setup. Versioned Java bindings are not a cross-version API guarantee.
  • Viewport: set the intended desktop or mobile viewport before navigation. Responsive layouts can change the document height and content.
  • Readiness: wait for a meaningful page element. A page-load event does not prove that deferred images, product data, or later sections have rendered.
  • Target conditions: control or record locale, currency, cookies, and session state when those affect the page. The research does not establish any retailer-specific India behavior.
  • Artifacts: store screenshots only where your test policy permits, and keep personal, payment, or account information out of saved artifacts.

What this method captures and what it does not guarantee

Approach Capture extent Portability Use when
WebDriver TakesScreenshot Current browsing context; the standard docs do not guarantee a full-document capture Standard WebDriver API You need the normal WebDriver screenshot for the current context
Chrome CDP Page.captureScreenshot Can capture beyond the viewport when the option is enabled Chrome-specific, versioned DevTools integration Your test is Chrome-based and you need a tall page image

Neither the API option nor a successful file write confirms that every intended page element loaded. Inspect the output. Sticky headers may appear differently from how you expect in a single tall image, and overlays or cookie dialogs may obscure content. Those are page-specific validation concerns, not a claim about any particular Indian ecommerce site.

Dynamic ecommerce pages and edge cases

Lazy-loaded product images

Some pages load images only as their image elements approach the viewport. A single readiness check near the top may leave lower images unloaded. If your test requires those images, scroll through the relevant sections before capturing, wait for the expected image elements or their load state, then measure the document again. Avoid assuming that all pages use the same lazy-loading strategy.

Infinite scroll and pagination

A page that adds products only after scrolling may not have a stable full-page height when you first measure it. Scroll through the content using a controlled test routine until the expected end condition is reached, then wait for the final section and take the screenshot. For paginated catalogs, capture each page explicitly if that is what the test needs; the CDP option does not navigate through pagination for you.

Responsive layouts and mobile emulation

Set the viewport before loading the page. A mobile viewport can trigger a different layout, different navigation, or different content loading behavior. If you use device emulation, configure it through the appropriate Selenium/CDP API for your binding and verify the rendered page before capture.

Very tall documents

A full-document image can be large and memory-intensive. If a page is exceptionally long, consider whether your test needs one image or whether validating sections separately would produce more manageable artifacts. The reviewed sources do not establish a universal maximum image height or reliability threshold, so check the behavior in your own browser and environment.

Locale and session state

Indian ecommerce pages may vary with locale, cookies, account state, delivery location, or other session conditions. This is a testing consideration, not a retailer-specific finding from the available evidence. Set the conditions your test requires and record them alongside the screenshot so a changed page can be diagnosed.

cURL, Python, and Node.js alternatives

These are not Selenium implementations. They are useful when the requirement is simply to obtain a screenshot from a URL through a screenshot API rather than run browser automation in your own test process.

cURL

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

Python

import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://example.com"},
    timeout=90,
)
r.raise_for_status()
with open("shot.webp", "wb") as f:
    f.write(r.content)

Node.js

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}`);
const bytes = new Uint8Array(await res.arrayBuffer());
await import('node:fs/promises').then(fs => fs.writeFile('shot.webp', bytes));

Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server. Its one-call API can return an image or PDF; see the 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
  • Cookie banners are accepted like a visitor, and 60+ known consent platforms, newsletter popups, and chat widgets are removed before the shot; each step can be turned off.
  • Bot checks, blank pages, timeouts, failed loads, and cache hits cost nothing. Responses identify the page verdict and billing status in headers.
  • An MCP server gives AI agents tools to take screenshots, get page information, and capture PDFs.
  • 1,000 screenshots a month are free with no card. Paid plans start at $5 for 3,000 screenshots.

Sign up free for 1,000 screenshots a month, with no card required.

Troubleshooting

Symptom Likely cause What to do
Code does not compile: missing v124 package or Page method The sample’s versioned CDP package does not match the dependency in your project. Use the DevTools Page binding corresponding to your Selenium/CDP version and adapt the method arguments to that API signature.
Chrome session fails to start Chrome and ChromeDriver major versions differ, or the driver is unavailable to Selenium. Check the browser and driver versions and ensure their major versions match.
Image shows only the viewport The beyond-viewport option was omitted, not enabled, or passed in the wrong position for the binding. Inspect the generated method signature and confirm that captureBeyondViewport is set to true.
Bottom products or images are missing Lazy loading, infinite scroll, or delayed content had not completed before capture. Scroll through the required content, wait for a page-specific end condition, then measure and capture.
Screenshot contains a consent dialog or overlay The site displayed an overlay in the active browser session. Handle it according to your test’s intended scenario, or use a capture workflow that supports removing common consent and popup elements.
Image dimensions do not match the intended device The viewport or emulation was set after navigation, or the page reflowed. Set the viewport before navigation and verify the layout and resulting image dimensions.
Screenshot is blank or unexpectedly sparse The page may still be loading, may have returned a bot check, or may need session-specific state. Check the browser page and logs, wait for the content your test requires, and verify the URL and session conditions.

Performance, reliability, and cost

With Selenium/CDP, your test owns the browser startup, navigation, waits, capture, and artifact storage. Runtime and memory depend on the page, browser, machine, viewport, and amount of content; the research provides no benchmark. Reuse a browser session when the surrounding test design allows it, keep waits tied to meaningful content, and avoid capturing more page area than the test needs.

For reliability, pin and record the Selenium, Chrome, and ChromeDriver versions used by the test, then validate an upgrade against representative target pages. A page-load event alone is not a reliable readiness signal for deferred content. Store enough context to reproduce the capture, such as viewport and relevant locale/session settings, while keeping sensitive data out of artifacts.

The local Selenium workflow has no ScreenshotNeo API charge, but it does require browser and test infrastructure. If you use ScreenshotNeo instead, its published plans are Free: 1,000 shots/month; Starter: $5 for 3,000; Growth: $15 for 15,000; Pro: $39 for 60,000; Scale: $99 for 250,000; Business: $249 for 1,000,000. Yearly billing gives two months free, and every feature is on every plan. Only clean shots are billed; the response includes verdict and billing headers.

FAQ

Does Selenium’s standard screenshot command guarantee a full page?

No. Selenium documents a screenshot of the current browsing context. The Chrome CDP method exposes an explicit beyond-viewport option.

Is this Java code cross-browser?

No. The CDP implementation is Chrome-specific, and the shown Java binding is versioned. Check your own Selenium and Chrome setup.

Does this guarantee a complete screenshot of an Indian retailer?

No. The available sources do not establish retailer-specific behavior. Validate the exact URL, locale, session, and page content in your authorized environment.

Can I use the result as a visual regression artifact?

Yes, if your test controls the conditions that affect rendering and checks the saved image. Treat the screenshot as an artifact of that browser, viewport, session, and moment.

Sources