ScreenshotNeo

BlogHow-to

How to capture full-page screenshots of Indian railway booking pages with Selenium

Use Selenium and Chrome DevTools Protocol for full-page captures on authorized test pages. Do not automate live IRCTC booking pages.

By the ScreenshotNeo team4 October 20268 min read

Short answer: For a Chrome page you own or are authorized to automate, use Selenium to call Chrome DevTools Protocol (CDP) Page.getLayoutMetrics and Page.captureScreenshot, setting captureBeyondViewport to true. Selenium’s ordinary screenshot methods capture the current browsing context; they do not promise a full-document image. Do not use Selenium to automate the live IRCTC booking service: IRCTC’s published terms prohibit automation and scripting software.

This guide covers full-page screenshots of Indian railway booking pages using local fixtures or approved staging environments. The code below is an implementation pattern for authorized Chrome pages; it has not been tested against IRCTC. A screenshot is not a ticket or reservation record. Keep the official booking record where one is relevant.

1. What “full-page screenshot” means in Selenium

A WebDriver screenshot such as driver.save_screenshot() or Selenium’s screenshot command captures the current browsing context, typically the viewport. Full-page capture means including content outside the visible viewport, down to the document’s measured dimensions. Selenium’s screenshot documentation shows current-context screenshots, while Chrome CDP exposes a separate option for capturing beyond the viewport. Selenium screenshot documentation.

In Chrome, the relevant CDP method is Page.captureScreenshot. Its captureBeyondViewport parameter is documented as false by default; set it to true and provide a clip covering the measured page dimensions. CDP returns the image as Base64 data. Chrome DevTools Protocol Page domain.

2. Check the IRCTC restriction before automating

IRCTC’s online booking terms state: “Use of automation software and/or Scripting Software is strictly prohibited.” Do not point the Selenium examples in this guide at the live booking flow or use them to interact with a booking account. Use a local test fixture, an approved staging page, or another page where you have permission to automate. Read the current IRCTC online booking terms before any use involving its services.

For context, a Ministry of Railways release dated 4 June 2025 reported anti-bot enforcement measures, including 2.5 crore suspected user IDs deactivated and 31,814 tickets booked in one minute on 22 May 2025. These are ministry-reported figures from that release, not predictions about an individual account or a claim that taking a screenshot triggers enforcement. Ministry of Railways release via Press Information Bureau.

3. Capture a full page with Selenium and Chrome

Prerequisites

  • Python and the Selenium Python binding installed in your project environment.
  • Chrome and a compatible Selenium-managed or explicitly configured ChromeDriver.
  • A page you own or have permission to automate. Use the Chrome and driver versions pinned or supported by your project.

Install Selenium with python -m pip install selenium. Selenium’s execute_cdp_cmd is the bridge used here to send Chrome DevTools Protocol commands. CDP fields and wrapper support can vary by Chrome and driver release, so validate the pattern against your installed versions and inspect the resulting file.

Runnable Python example

Save as capture_full_page.py. Point TEST_URL at an authorized test or staging page. The example waits for the document to finish loading, measures the document, requests a PNG beyond the viewport, and decodes the response to a file. Replace the readiness condition with an application-specific check when content is rendered asynchronously.

import base64
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait

TEST_URL = "https://example.test/page"  # Use only an authorized test page.
OUTPUT_PATH = "full-page.png"

options = webdriver.ChromeOptions()
# For a headless test run, uncomment the next line:
# options.add_argument("--headless=new")

driver = webdriver.Chrome(options=options)
try:
    driver.get(TEST_URL)
    WebDriverWait(driver, 30).until(
        lambda browser: browser.execute_script("return document.readyState") == "complete"
    )

    # Add a page-specific wait here for asynchronous content, for example:
    # WebDriverWait(driver, 20).until(
    #     lambda browser: browser.find_element("css selector", "[data-test='results']").is_displayed()
    # )

    metrics = driver.execute_cdp_cmd("Page.getLayoutMetrics", {})
    content = metrics.get("cssContentSize") or metrics.get("contentSize")
    if not content:
        raise RuntimeError("Chrome did not return document content dimensions")

    result = driver.execute_cdp_cmd(
        "Page.captureScreenshot",
        {
            "format": "png",
            "captureBeyondViewport": True,
            "fromSurface": True,
            "clip": {
                "x": 0,
                "y": 0,
                "width": content["width"],
                "height": content["height"],
                "scale": 1,
            },
        },
    )
    with open(OUTPUT_PATH, "wb") as image_file:
        image_file.write(base64.b64decode(result["data"]))
    print(f"Saved {OUTPUT_PATH} ({content['width']} × {content['height']} CSS pixels)")
finally:
    driver.quit()

For reference, see the CDP layout metrics method and capture screenshot method. The example checks both newer cssContentSize and fallback contentSize fields because protocol versions differ.

Steps to adapt it to a railway-page test fixture

  1. Load an approved staging page or a local HTML fixture that reproduces the layout you need to test.
  2. Wait for the specific result table, fare summary, or status region your test depends on. document.readyState alone does not guarantee an application has finished its asynchronous rendering.
  3. If images or cards load as the page scrolls, scroll through the authorized page and wait for the relevant elements before measuring. The screenshot command does not guarantee lazy content has loaded.
  4. Measure after content is ready, capture with CDP, and inspect the PNG from top to bottom for clipped rows, missing images, overlays, and blank regions.
  5. Store test captures securely if the fixture includes personal or booking-like data; use synthetic data for repeatable tests.

4. Handle lazy content and page state

Full-page capture expands the image area; it does not cause every application component to load. Lazy images may load only when they approach the viewport, and content may depend on a user action or delayed API response. Scroll in the authorized test context, wait for the expected content, then measure and capture. Avoid fixed sleeps when a condition that checks the needed content is available.

Sticky headers, open menus, cookie banners, chat widgets, and other overlays are part of the rendered state. Prepare the intended state in your fixture or test setup. Do not use page manipulation to evade a live service’s restrictions. If you need a record rather than a raster image, a PDF may be easier to read for a very long page; Chrome documents headless screenshots and PDF output, and notes that full-page capture requires more than the basic screenshot flag. Chrome headless documentation.

5. Choose the capture method for the job

Method Result Use it when
Selenium WebDriver screenshot Current browsing context, usually viewport You need a viewport or element screenshot in an ordinary WebDriver test.
Chrome CDP Page.captureScreenshot Can include content beyond viewport when configured and clipped to page dimensions You need a full-page PNG from an authorized Chrome automation context.
Browser print to PDF Paginated document The page is very tall or a readable record is more useful than one large raster.

For Selenium’s standard screenshot APIs, see Selenium WebDriver documentation. For Chrome’s capture parameters, see the CDP protocol reference.

6. Troubleshooting

Symptom Likely cause Fix
Only the visible viewport appears The code called a normal WebDriver screenshot, or CDP capture omitted captureBeyondViewport: true. Use Chrome’s CDP Page.captureScreenshot call and set the flag and page-sized clip.
The lower portion is blank or missing Async rendering or lazy loading had not completed when dimensions were measured. Wait for the relevant page condition; scroll to trigger authorized lazy content; measure again after it appears.
The dimensions are absent or zero The installed Chrome/CDP version returned different metric fields, or the page had not laid out. Check cssContentSize and contentSize, wait for the page layout, and inspect the response from Page.getLayoutMetrics.
execute_cdp_cmd is unavailable or rejects the command The driver is not Chrome-compatible, or the Selenium/Chrome combination exposes different CDP support. Use a Chrome WebDriver session, check the installed Selenium and browser versions, and consult their version-specific documentation.
The file cannot be decoded or opened The response did not contain screenshot data, or it was not decoded as Base64 PNG. Check that the CDP command returned a data field, decode it with base64.b64decode, and save bytes in binary mode.
Capture is enormous, slow, or fails The document is very tall or wide and creates a large raster. Capture logical sections or print to PDF. Do not assume one huge image is practical for every page.
A live IRCTC page is the target The site’s terms prohibit automation and scripting software. Stop the automation workflow. Use only methods allowed by current terms and retain official booking records where relevant.

7. Performance, reliability, and cost

  • Performance: Full-page raster size grows with the page’s pixel area. Tall tables and high-density imagery can increase capture time, memory use, and output size. Capture only the dimensions needed; split very long pages or use PDF.
  • Reliability: Pin compatible Chrome, ChromeDriver, and Selenium versions in CI. Wait for application-specific readiness, measure only after layout stabilizes, and inspect output images when changing browser versions.
  • Repeatability: Use a stable staging fixture, fixed viewport and test data. Dynamic content, animations, time-sensitive results, and fonts can change the image between runs.
  • Cost: Selenium itself does not charge per screenshot, but your browser runner, CI minutes, storage, and image handling may have costs under their providers’ terms. This workflow does not authorize automation of a restricted production site.

8. Or skip the browser setup

For pages you are permitted to capture, ScreenshotNeo is a website screenshot API and MCP server. Its one-request API returns a screenshot or PDF, and its supported parameter names include those used by other screenshot APIs. See the ScreenshotNeo API documentation.

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

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://example.test/page"},
    timeout=90,
)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({
  access_key: 'YOUR_API_KEY',
  url: 'https://example.test/page'
});
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot request failed: ${res.status}`);
const image = Buffer.from(await res.arrayBuffer());
await import('node:fs/promises').then(fs => fs.writeFile('shot.webp', image));
  • Cookie and consent banners, newsletter popups, and chat widgets are removed before capture; each step can be turned off.
  • Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed. Responses identify the page verdict and billing status in headers.
  • An MCP server lets AI agents use take_screenshot, get_page_info, and capture_pdf.
  • The Free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. Every feature is on every plan.

Use it only for URLs you are authorized to capture and in line with the site’s terms. Sign up for 1,000 free screenshots a month with no card.

9. FAQ

Does a full-page screenshot prove a railway ticket was booked?

No. A screenshot is an image of a page state, not a ticket or reservation record. Keep the official booking confirmation and records.

Can I use the same CDP code in Firefox?

This example is for Chrome’s DevTools Protocol through a Chrome WebDriver session. Browser-specific full-page capture methods differ; use the documentation for the browser and driver in your project.

Will CDP capture every lazy-loaded image automatically?

No. Ensure required content has loaded before capture, and inspect the resulting image.

Can I capture only a long results table?

For an authorized test, you can adapt the fixture and capture strategy to the relevant region or split the page into sections. Ensure the captured dimensions and content match the test assertion; one page-sized image is not always the clearest artifact.