ScreenshotNeo

BlogHow-to

How to Capture a Webpage as an Image Using Selenium for Documentation

Capture consistent webpage screenshots for documentation with Selenium. Choose the right scope, wait for dynamic content, and save reliable PNGs.

By the ScreenshotNeo team4 October 20267 min read

Use Selenium WebDriver to open the page, set the viewport, wait for the content your documentation needs, and call driver.save_screenshot("page.png"). In Python this saves the current browser window as a PNG. For a component, capture the element; for the entire long document, use Firefox’s documented full-page API where supported.

1. Choose what the screenshot should contain

Decide the capture scope before writing the script. A viewport screenshot is usually right for documenting what a user sees at a particular screen size. An element screenshot isolates one component. A full-page screenshot captures content beyond the current viewport, but the documented full-page WebDriver method here is Firefox-specific.

Need Route Notes
Visible browser window driver.save_screenshot("page.png") Python WebDriver saves the current window as PNG.
One component element.screenshot("component.png") Locate the element after it is present and visible.
Entire long page Firefox save_full_page_screenshot Check browser and binding support; do not assume it is portable.
Simple Chrome capture Chrome Headless CLI Separate from Selenium; dimensions can be set with --window-size.

2. Install Selenium and a browser

Install the Python binding with python -m pip install selenium. You also need a supported browser, such as Chrome or Firefox. Selenium Manager can manage drivers in standard setups; environments with restricted network access or pinned browser builds may need an explicitly provisioned compatible driver.

python -m pip install selenium

3. Capture the current window in Python

This runnable example creates the output directory, chooses a stable viewport, waits for a page-specific element, checks the API return value, and always closes the browser. Replace the URL and readiness selector with the page and content your documentation requires.

from pathlib import Path
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

url = "https://example.com"
output = Path("artifacts/page.png").resolve()
output.parent.mkdir(parents=True, exist_ok=True)

options = webdriver.ChromeOptions()
options.add_argument("--headless")

# Set an explicit viewport so responsive layouts are repeatable.
options.add_argument("--window-size=1440,1000")
driver = webdriver.Chrome(options=options)
try:
    driver.set_page_load_timeout(45)
    driver.get(url)

    # Replace "main" with a selector for the content your docs need.
    WebDriverWait(driver, 20).until(
        EC.visibility_of_element_located((By.CSS_SELECTOR, "main"))
    )

    saved = driver.save_screenshot(str(output))
    if not saved:
        raise OSError(f"Could not save screenshot to {output}")
    print(f"Saved {output}")
finally:
    driver.quit()

Selenium’s Python API describes save_screenshot as saving the current window to PNG. Use an absolute output path and a .png suffix in automation, and check its boolean result.

4. Capture one element

Use the element’s screenshot method when the documentation calls for a chart, card, form, or other component rather than the surrounding page. Wait until it is visible before saving.

from pathlib import Path
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

output = Path("artifacts/chart.png").resolve()
output.parent.mkdir(parents=True, exist_ok=True)
driver = webdriver.Chrome()
try:
    driver.get("https://example.com/dashboard")
    chart = WebDriverWait(driver, 20).until(
        EC.visibility_of_element_located((By.CSS_SELECTOR, "#revenue-chart"))
    )
    if not chart.screenshot(str(output)):
        raise OSError(f"Could not save screenshot to {output}")
finally:
    driver.quit()

Element capture does not mean the full page is captured. If the element is outside the viewport or covered by a sticky overlay, scroll it into view or adjust the page before capture.

5. Full-page capture and alternative output forms

For an entire document in Firefox, Selenium’s Firefox API documents save_full_page_screenshot. Confirm that the installed Firefox driver and Python binding expose the method before relying on it. It is not the portable default for Chrome and other bindings.

from selenium import webdriver

driver = webdriver.Firefox()
try:
    driver.get("https://example.com")
    # Wait for the page content your capture requires before this call.
    if not driver.save_full_page_screenshot("full-page.png"):
        raise OSError("Could not save full-page screenshot")
finally:
    driver.quit()

The Python API also provides screenshot bytes and Base64 output for workflows that upload or embed an image instead of writing directly to disk. Those are useful when another part of your program handles storage. Keep the output format and encoding explicit at that boundary.

6. Control readiness, viewport, and repeatability

  1. Set the viewport. Window dimensions change responsive breakpoints and visible content. Use the same dimensions for each documentation run.
  2. Wait for the right condition. Navigation returning does not guarantee that client-rendered content, fonts, charts, or images have finished loading. Wait for a meaningful selector or state, not an arbitrary sleep where possible.
  3. Handle lazy content deliberately. If the page loads images as they approach the viewport, scroll through the relevant area and wait for image completion before a full-document capture. A viewport screenshot only needs assets in that viewport.
  4. Use deterministic page state. Documentation pages that depend on accounts, live data, animations, rotating banners, or time-sensitive content can vary. Use a stable fixture or test account where appropriate, and disable animation through application styling if you control the page.
  5. Check the artifact. Verify that the file exists, opens, has the intended dimensions, and contains the correct content. A successful browser call does not validate the image’s visual quality.

7. Chrome Headless command-line alternative

If Selenium orchestration is unnecessary, Chrome documents a direct headless screenshot command. This is a browser CLI workflow, not WebDriver code:

chrome --headless --screenshot --window-size=1440,1000 https://example.com

Chrome writes screenshot.png in the current directory. The documented --timeout option sets a maximum capture delay for screenshot, DOM dump, and PDF operations; it cannot guarantee that a particular application’s asynchronous content is ready. For application-specific readiness, use Selenium and wait on the page state.

8. Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server. Make one GET request to capture a URL; see the ScreenshotNeo API documentation for parameters.

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}`);
const fs = await import('node:fs/promises');
await fs.writeFile('shot.webp', Buffer.from(await res.arrayBuffer()));
  • Cookie banners and consent prompts, popups, and chat widgets are removed before the shot; each cleanup step can be turned off.
  • Bot checks, blank pages, and failed loads are never billed. Response headers identify the page verdict and billing status.
  • An MCP server lets AI agents use screenshot, page-info, and PDF capture tools.
  • 1,000 screenshots a month are free with no card; paid plans start at $5 for 3,000.

Sign up for ScreenshotNeo’s free plan to get 1,000 screenshots a month with no card.

9. Troubleshooting Selenium screenshots

Symptom Likely cause Fix
Driver creation fails Browser/driver mismatch, missing browser, or restricted driver download. Install a supported browser, check Selenium Manager access, or provision a compatible driver explicitly.
Screenshot is blank or incomplete Capture happened before app rendering or important assets finished. Wait for the specific content, image, or application-ready condition; inspect the resulting image.
Wrong responsive layout Viewport varies between local and CI runs. Set window dimensions before navigation or capture and keep them consistent.
Output file is missing Relative path points somewhere unexpected, directory is absent, or write failed. Resolve the path, create parent directories, check the returned boolean, and verify filesystem permissions.
Timeout during navigation Slow or never-ending page load, often due to third-party resources. Set a page-load timeout and consider an appropriate page-load strategy; then wait for the content needed rather than waiting for every late request.
Full-page method is unavailable The installed driver or binding does not provide the Firefox-specific method. Use the supported Firefox setup, or choose a different capture strategy and verify its behavior for your browser.
Element image is clipped or obscured Element is off-screen, covered, or its contents have not rendered. Scroll it into view, wait for visibility and content readiness, and remove or hide obstructing page elements if appropriate.

10. Performance, reliability, and cost

Each Selenium capture starts or uses a browser session, so reusing a session for a batch can avoid repeated startup overhead. Close it in a finally block to release browser processes even when navigation or file writing fails. Set practical page and condition timeouts so a broken page does not hold a CI job indefinitely.

For repeatable documentation, pin the browser environment where practical, use stable test data, and record the viewport and target URL alongside the artifact. Browser rendering can vary with browser version, fonts, operating system, device scale, and live page content. Selenium itself does not charge per screenshot; your infrastructure costs include browser runtime, compute, storage, and any network or CI usage.

If captures run at scale or need consent cleanup, verdict-based billing, async jobs, bulk URLs, or an agent-facing MCP interface, compare the setup cost of maintaining browsers with ScreenshotNeo’s plan limits and features on its website. Its listed plans range from 1,000 free monthly shots to paid plans from $5; every feature is available on every plan.

11. Frequently asked questions

Does Selenium save screenshots as PNG or JPEG?

The documented Python save_screenshot method writes PNG. Treat the output filename and actual format consistently; convert afterward if another format is required.

Can Selenium capture a screenshot without showing a browser window?

Yes. Configure the browser for headless operation when creating the WebDriver, then navigate and capture as usual.

Does a Selenium screenshot include browser chrome?

WebDriver captures the browser’s page window, not the surrounding desktop or browser interface.

Can I use the same full-page method in every browser?

No. The cited full-document method is documented for Firefox. Check the specific browser and language binding API before depending on full-page behavior.

Where can I confirm Selenium’s current method behavior?

Use the official Selenium documentation and the relevant binding API reference. The examples here follow the documented Python screenshot behavior and Firefox full-page API.

Sources