ScreenshotNeo

BlogHow-to

How to Automate Screenshots of Indian Government Service Portals with Selenium

Capture authorized portal pages with Selenium using explicit waits, reproducible browser settings, and the right screenshot scope. Includes runnable Python code and troubleshooting.

By the ScreenshotNeo team4 October 20268 min read

Use Selenium WebDriver to open the portal page, wait for the specific content you need to appear, then save a screenshot. In Python with Chromium, driver.save_screenshot() saves the current window as a PNG. For a full-document screenshot, Selenium’s Firefox Python API documents get_full_page_screenshot_as_file(). The method and capture scope depend on the browser binding, so choose and verify them deliberately.

This guide uses Python and Chrome/Chromium for a viewport screenshot. It does not establish that any particular government portal permits automated access. Check the portal’s current terms and access policy, use an authorized route and account, and stop if a CAPTCHA or other human-verification barrier appears.

1. Check access and define the capture

Before writing the script, specify the portal, route, and state to capture: initial page, content after a permitted interaction, or an error state. Government portal behavior and access conditions differ. Generic Selenium instructions cannot determine whether automation is permitted for an unnamed service.

For repeatable captures, record the browser and version, viewport dimensions, locale or display settings that affect the page, capture time, and whether the image is viewport or full-document. GIGW 3.0 offers recommended guidance for central, state, and local government websites and apps, with aims that include usability, security, and accessibility; it does not replace a portal’s own access policy. GIGW scope and objective.

2. Install Selenium and a browser

Install Selenium in an isolated Python environment. Selenium Manager can arrange a compatible driver for supported setups when the browser is installed; in restricted or managed environments, install and configure the browser and driver according to local policy.

python -m venv .venv
# macOS/Linux
. .venv/bin/activate
# Windows PowerShell: .venv\Scripts\Activate.ps1
python -m pip install --upgrade selenium

The example below assumes Chrome or Chromium is available. Set PORTAL_URL to the exact authorized URL and READY_SELECTOR to a stable element that indicates the content you intend to capture has appeared. The example intentionally fails if that condition is not met.

3. Navigate, wait for the page-specific condition, and capture

import os
from datetime import datetime, timezone
from pathlib import Path

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException, WebDriverException

PORTAL_URL = os.environ.get("PORTAL_URL", "https://example.gov.in/")
READY_SELECTOR = os.environ.get("READY_SELECTOR", "main")
OUT = Path("portal-viewport.png")

options = Options()
# For a visible browser, remove the next line.
options.add_argument("--headless=new")
options.add_argument("--window-size=1440,1000")

# Keep implicit waits at their default (zero); use the explicit wait below.
driver = webdriver.Chrome(options=options)
try:
    driver.set_page_load_timeout(60)
    driver.get(PORTAL_URL)

    wait = WebDriverWait(driver, 30)
    wait.until(EC.visibility_of_element_located(("css selector", READY_SELECTOR)))

    # Capture the current browser window as a PNG.
    saved = driver.save_screenshot(str(OUT))
    if not saved or not OUT.is_file() or OUT.stat().st_size == 0:
        raise OSError(f"Screenshot was not written: {OUT}")

    stamp = datetime.now(timezone.utc).isoformat()
    print(f"Saved {OUT} ({OUT.stat().st_size} bytes), URL={driver.current_url}, UTC={stamp}")
except TimeoutException as exc:
    raise SystemExit(
        f"Timed out waiting for page readiness or selector {READY_SELECTOR!r}. "
        "Check the selector, portal response, and whether human verification is shown."
    ) from exc
except WebDriverException as exc:
    raise SystemExit(f"Browser navigation or capture failed: {exc}") from exc
finally:
    driver.quit()

Run it by setting environment variables rather than editing the script for each target:

PORTAL_URL='https://example.gov.in/service' READY_SELECTOR='main .service-content' python capture_portal.py

Replace the example domain and selector with the intended portal’s actual values. Avoid putting credentials in source code or logs. If a page requires authentication, use only an approved account and a method allowed by that service.

4. Choose the wait that matches the page

A navigation reaching document readiness does not guarantee that JavaScript-rendered content is present or visible. Wait for an observable condition tied to the content you plan to capture. Selenium’s waiting strategies document explicit waits and caution that mixing implicit and explicit waits can make timeout behavior unpredictable.

Page behavior Useful condition
A main content region appears visibility_of_element_located
A specific heading or status is inserted text_to_be_present_in_element
A loading spinner disappears invisibility_of_element_located
A permitted button enables after data loads element_to_be_clickable
An application updates a known state A custom wait that checks that state

Use a fixed sleep only when the page has a known delay that cannot be observed through a condition; it adds delay to fast runs and can still be too short on slow ones. Do not combine a nonzero implicit wait with explicit waits.

5. Viewport versus full-page screenshots

driver.save_screenshot("portal.png") in the documented Chromium Python API captures the current window as a PNG. It does not mean “capture every page below the fold.” Make the browser window size explicit if the viewport matters.

Selenium’s Firefox Python API separately documents driver.get_full_page_screenshot_as_file("portal.png") for a full-document image. Confirm that the browser and language binding in your installation support the method. Do not assume the Firefox full-page method exists in Chromium or every Selenium binding. See the Chromium Python screenshot API and Firefox Python full-page API.

# Chromium: current window / viewport PNG
ok = driver.save_screenshot("portal-viewport.png")

# Firefox Python binding: full document, where supported
ok = driver.get_full_page_screenshot_as_file("portal-full-page.png")

Very long pages can produce large images and may include content that loads only as the page is scrolled. If full-document output is essential, verify that lazy-loaded sections are present and that the selected browser method captures them as expected. Preserve the original page state and output scope in the capture record.

6. Handle portals with dynamic or localized content

  • Loading indicators: wait for the indicator to disappear and the target content to become visible.
  • Locale-sensitive output: record language, timezone, and viewport. Do not assume a locale option changes server-side content; the portal may use account or request settings.
  • Dialogs and overlays: capture the state that is actually needed. Interact only through authorized, ordinary page controls; do not remove security challenges.
  • Session state: a fresh browser may show a landing page or sign-in instead of the intended service. Use only approved authentication procedures and protect session data.
  • CAPTCHA or human verification: stop the automated flow and report that human action is required. GIGW accessibility guidance discusses text alternatives and alternatives using different sensory modes; that is accessibility context, not permission to defeat a verification control. See the official GIGW guidance.

7. Troubleshooting

Symptom Likely cause Fix
TimeoutException on the explicit wait The selector is wrong, content did not load, or the page is in a different state. Inspect the page manually, choose a stable selector for the desired content, and distinguish a portal error or verification page from a normal timeout.
Screenshot is blank or shows a spinner The wait condition only matched a shell element, not the loaded content. Wait for the actual content or expected text, and check whether the portal returned an error or maintenance page.
Only the top portion appears The current-window API captures the viewport. Use a documented full-page method for the chosen browser binding, such as the Firefox Python API, or explicitly treat the output as a viewport capture.
Chrome or driver startup fails Browser unavailable, incompatible setup, or managed environment restrictions. Install a supported browser, check Selenium and browser setup documentation, and configure the driver permitted in that environment.
Capture differs between runs Variable viewport, locale, session state, page content, or timing. Fix and record the browser context; wait on page-specific state and retain capture metadata.
Portal displays CAPTCHA or access denial The service requires human verification or restricts automated access. Stop. Use an approved human workflow or an authorized test environment; do not attempt to bypass the barrier.
Screenshot file is missing or empty Write failure, invalid path, or screenshot command returned false. Check the process’s working directory and write permissions, inspect the boolean result, and verify file size.

8. Reliability, performance, and cost

Reliability comes from making the capture state explicit: use a stable selector or text condition, set a bounded page-load timeout and explicit-wait timeout, record the final URL, and verify the saved file. Capture failures should be reported as failures rather than silently treated as valid images. Do not retry indefinitely; repeated automated requests can burden a public service or conflict with its rules.

Capture time depends on the portal response, browser startup, and how long the chosen readiness condition takes; the research sources provide no benchmark. Headless mode can simplify unattended runs, while a visible browser is useful for diagnosing unexpected page state. Browser automation also consumes machine resources. Review the portal’s policies and any applicable network or cloud compute costs before scheduling captures.

Or skip the browser setup

For a one-call screenshot API alternative, ScreenshotNeo takes a URL and returns a screenshot or PDF. Cookie banners are accepted like a visitor and removed, along with 60+ known consent platforms, newsletter popups, and chat widgets; each step can be turned off. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and the response includes page-verdict and billing headers. Its MCP server gives AI agents tools to take screenshots, get page information, and capture PDFs. The free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000. Check the ScreenshotNeo API documentation and confirm the target portal permits your intended access.

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

Create a free ScreenshotNeo account for 1,000 screenshots a month, with no card required.

FAQ

How do I take a screenshot of a government website with Selenium?

Navigate to the authorized page, wait for a page-specific readiness condition, and call the screenshot method supported by your browser binding. Verify the output file and the state shown.

How do I wait for a portal page to finish loading before taking a screenshot?

Wait for the element, text, or state that represents the content you need. Document readiness alone may not mean JavaScript-driven content has appeared; avoid mixing implicit and explicit waits.

Can Selenium capture a full page in every browser?

No universal method should be assumed. The Chromium Python API documents current-window PNG capture; the Firefox Python API documents a full-document screenshot method. Check support for the specific browser and binding.

Can I automate a CAPTCHA on a government portal?

This workflow stops at human-verification barriers. Use the portal’s authorized human process or an approved test environment.

Does GIGW tell me whether a specific portal allows Selenium?

No. GIGW is recommended guidance for government websites and apps; the specific portal’s current terms and access policy determine whether your use is allowed.