Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

In Python, the shortest Selenium screenshot script is driver.get(...) followed by driver.save_screenshot("screenshot.png"). Create the browser in a try block, check the method’s Boolean result, and always call driver.quit() in finally so the browser session closes even when navigation or saving fails.

What you need before writing the script

Selenium WebDriver controls a real browser through a language binding, a browser, and the browser’s driver implementation. This tutorial uses the Python binding and Chrome. The same WebDriver capability exists in other Selenium language bindings, but method names and setup syntax differ.

  • A supported Python installation and an isolated virtual environment are recommended for project dependencies.
  • The Selenium Python package installed in that environment.
  • A browser such as Google Chrome installed on the machine running the script.

Modern Selenium documentation says Selenium Manager generally finds and manages the driver for supported browser and platform combinations when you instantiate a WebDriver. Older projects may still contain manual driver-path configuration, but do not add a hard-coded path unless your environment requires it.

Install Selenium in an isolated environment

python -m venv .venv
# macOS/Linux
source .venv/bin/activate
# Windows PowerShell
.venvScriptsActivate.ps1
python -m pip install selenium

Use the activation command appropriate to your shell. If your organization manages Python packages centrally, install Selenium through that approved process instead.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The basic Python screenshot script

This complete example opens a page, saves the current browser window as a PNG, detects a reported write failure, and closes the browser regardless of what happens.

from selenium import webdriver

URL = "https://example.com"
OUTPUT = "screenshot.png"

driver = webdriver.Chrome()
try:
    driver.get(URL)
    saved = driver.save_screenshot(OUTPUT)
    if not saved:
        raise OSError(f"Selenium could not save {OUTPUT}")
    print(f"Saved {OUTPUT}")
finally:
    driver.quit()

Run it from the directory where you want the output file:

python screenshot.py

save_screenshot() captures the current browsing context and writes a PNG file. A relative path such as screenshot.png is resolved from the process’s current working directory, which may not be the same directory as your Python file. For predictable automation, pass an absolute path or construct one with Python’s pathlib.

Use an absolute output path

from pathlib import Path
from selenium import webdriver

output = Path("artifacts") / "home.png"
output.parent.mkdir(parents=True, exist_ok=True)

driver = webdriver.Chrome()
try:
    driver.get("https://example.com")
    if not driver.save_screenshot(str(output.resolve())):
        raise OSError("Screenshot write failed")
finally:
    driver.quit()

The Python API documents a Boolean return value: a successful save reports true, while an I/O error reports false. Checking it is useful in build jobs, test suites, and scheduled scripts where silently missing artifacts are costly.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Control when the screenshot is taken

A screenshot is a picture of the page state at the moment Selenium captures it. Navigation returning does not necessarily mean every image, animation, or application component is visually settled.

Wait for a specific element

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

 driver = webdriver.Chrome()
try:
    driver.get("https://example.com/dashboard")
    WebDriverWait(driver, 20).until(
        EC.visibility_of_element_located((By.CSS_SELECTOR, "main.dashboard"))
    )
    if not driver.save_screenshot("dashboard.png"):
        raise OSError("Screenshot write failed")
finally:
    driver.quit()

Replace the selector with an element that genuinely indicates the page is ready. Waiting for a fixed number of seconds can be appropriate for a known animation, but an explicit condition is usually less wasteful and less fragile.

Set a repeatable window size

driver.set_window_size(1440, 1000)

Place this before navigation or capture when you need a consistent viewport. Window dimensions affect responsive breakpoints and therefore the layout shown in the image. Equal dimensions still do not guarantee pixel-identical files: browser and operating-system versions, fonts, device scale, page timing, and dynamic content can change pixels.

You can also use Selenium’s fullscreen or window-management methods when that matches the test objective. Record the chosen dimensions in your automation configuration rather than relying on whatever size the desktop happened to have.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Capture an element instead of the whole window

Use a WebElement screenshot when the requirement is a component, card, chart, or other bounded element rather than the visible browser window.

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

 driver = webdriver.Chrome()
try:
    driver.get("https://example.com")
    panel = WebDriverWait(driver, 20).until(
        EC.visibility_of_element_located((By.CSS_SELECTOR, "section.pricing"))
    )
    if not panel.screenshot("pricing-panel.png"):
        raise OSError("Element screenshot write failed")
finally:
    driver.quit()

The element must be present and rendered. If it is outside the viewport, Selenium’s browser implementation may scroll it into view as part of the operation; for reliable results, explicitly scroll or wait for visibility first.

Choose a file, PNG bytes, or Base64

The Python API exposes three useful output forms. They are alternatives for different downstream workflows, not image-quality levels.

Method Result Use it when
driver.save_screenshot(path) Writes a PNG file and returns a Boolean status You need an artifact on disk for review, CI, or archival
driver.get_screenshot_as_png() Returns raw PNG bytes You will upload, hash, transform, or inspect the image in memory
driver.get_screenshot_as_base64() Returns Base64-encoded image data You need to embed the image in HTML or transmit text data

Save bytes yourself

from selenium import webdriver

 driver = webdriver.Chrome()
try:
    driver.get("https://example.com")
    png_bytes = driver.get_screenshot_as_png()
    with open("from-bytes.png", "wb") as image_file:
        image_file.write(png_bytes)
finally:
    driver.quit()

Embed Base64 in HTML

from selenium import webdriver

 driver = webdriver.Chrome()
try:
    driver.get("https://example.com")
    encoded = driver.get_screenshot_as_base64()
    html = f'Page screenshot'
    with open("preview.html", "w", encoding="utf-8") as page:
        page.write(html)
finally:
    driver.quit()

Does Selenium capture a full page?

The basic save_screenshot() call captures the current browsing context, not a guaranteed full document from the top of the page to its bottom. The exact result can depend on browser implementation and window state. If you need a full-page image, investigate the full-page capability exposed by your chosen browser and Selenium version, or use a dedicated capture service designed for document-length screenshots. Do not assume that enlarging the viewport produces a true full-page capture: it can change responsive layout and still omit content that loads only after scrolling.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For long-page testing with Selenium, a practical approach is to keep the viewport fixed, scroll deliberately to trigger lazy content, wait for the relevant elements, and capture sections or elements separately. Stitching those sections requires your own image-processing logic and careful handling of sticky headers and overlapping content.

Useful variations for real automation

Capture after a click

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

 driver = webdriver.Chrome()
try:
    driver.get("https://example.com")
    WebDriverWait(driver, 15).until(
        EC.element_to_be_clickable((By.CSS_SELECTOR, "button.more"))
    ).click()
    WebDriverWait(driver, 15).until(
        EC.visibility_of_element_located((By.CSS_SELECTOR, "div.details"))
    )
    driver.save_screenshot("expanded.png")
finally:
    driver.quit()

Run headlessly on a server

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_argument("--headless")
options.add_argument("--window-size=1440,1000")
driver = webdriver.Chrome(options=options)
try:
    driver.get("https://example.com")
    if not driver.save_screenshot("server-shot.png"):
        raise OSError("Screenshot write failed")
finally:
    driver.quit()

Headless mode is useful in CI and containers, but its rendering environment still matters. Install the required browser dependencies in the image, choose a window size explicitly, and retain the screenshot as a failed-test artifact when diagnosing differences.

Capture several URLs safely

from pathlib import Path
from selenium import webdriver

pages = {
    "home": "https://example.com",
    "example": "https://example.com/about",
}
out = Path("shots")
out.mkdir(exist_ok=True)

driver = webdriver.Chrome()
try:
    for name, url in pages.items():
        driver.get(url)
        target = out / f"{name}.png"
        if not driver.save_screenshot(str(target)):
            raise OSError(f"Could not save {target}")
finally:
    driver.quit()

For production jobs, catch errors per URL if one failed page should not prevent the remaining captures, and record the URL, exception, and output path in your job log.

Troubleshooting Selenium screenshots

“Unable to obtain driver” or browser startup failure

Confirm that the browser is installed and can launch under the same account as the script. Upgrade Selenium in the virtual environment, check that the browser and driver are compatible, and inspect restrictions imposed by a container, CI runner, proxy, or corporate policy. Selenium Manager handles many supported modern combinations, but it cannot fix a missing browser or an environment that blocks driver discovery or download.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The script runs but no image appears

Print or log the absolute output path. A relative path may point to the process’s working directory. Ensure the parent directory exists and that the account has write permission. Check the Boolean returned by save_screenshot() and catch filesystem exceptions rather than assuming the call succeeded.

The screenshot is blank or incomplete

Wait for a meaningful element, not merely a successful navigation call. Check for redirects, authentication, bot challenges, iframes, lazy-loaded images, and JavaScript errors. If content is inside an iframe, switch to that frame before locating its elements. If content appears only after scrolling, scroll and wait before capture.

The layout changes between runs

Set the window size, use the same browser and operating-system image, keep fonts consistent, and make the capture wait for a stable application state. Disable or control animations where your test permits it. Dynamic advertisements, timestamps, personalized data, network timing, and device scale can still produce legitimate pixel differences.

The element screenshot fails

Verify the selector, wait for visibility, and make sure the element is not detached and replaced by a frontend re-render. Re-locate the element immediately before calling screenshot() if the page frequently rebuilds that component.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Performance, reliability, and cost considerations

Launching a fresh browser for every URL is simple and isolates failures, but startup is expensive. Reusing one driver for a controlled batch reduces startup overhead; reset cookies, local storage, and application state when isolation matters. Always quit the driver in a finally block so failed jobs do not leave orphaned browser processes.

Use explicit waits instead of large fixed delays. They reduce idle time on fast runs while still allowing slower pages to become ready. Keep screenshots at the dimensions needed for the task: very large viewports and many high-resolution images consume more memory and disk space. Store diagnostic screenshots only as long as your retention policy requires, especially when pages contain personal or confidential data.

Selenium itself is a browser-automation workflow. It consumes the compute and network resources of the machine running the browser; the basic API does not impose a per-screenshot service charge. Your infrastructure, browser execution time, storage, and network costs still apply.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If you only need a clean website capture rather than an interactive browser test, ScreenshotNeo provides a single-request screenshot API. Before capture it accepts cookie or consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed as clean shots, and the response identifies the result with X-Page-Verdict and X-Billed headers.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

It supports PNG, JPEG, WebP, and PDF output, full-page captures with lazy images loaded, CSS-selector element captures, dark mode, device presets or custom viewports, retina scale, custom CSS and JavaScript, clicks, waits, request blocking, headers, cookies, user agents, Authorization, timezone, geolocation, transparent backgrounds, resizing, configurable caching, signed image links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, a usage API, and an OpenAPI specification. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.

cURL

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

Python

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)

Node.js

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

See the ScreenshotNeo documentation for request options and response handling. The Free plan includes 1,000 screenshots per month without a card; paid plans start at $5 for 3,000 screenshots. Create a free ScreenshotNeo account to get started.

FAQ

What file format does Selenium’s Python screenshot method save?

save_screenshot() saves a PNG image. Use the bytes or Base64 methods when the next step needs data in memory rather than a file.

Should I call close() or quit()?

Use quit() at the end of the script to end the WebDriver session and close its browser windows. Put it in finally for cleanup on errors.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Can I take a screenshot without displaying Chrome?

Yes. Configure Chrome’s headless option, set a deliberate window size, and ensure the server or container has the browser libraries and permissions it needs.

Why does an element screenshot differ from a window screenshot?

An element screenshot is bounded to the selected WebElement; a window screenshot represents the current browsing context. Choose the one matching the artifact you need.

Frequently Asked Questions

Does Selenium automatically wait for images before taking a screenshot?

No. Build an explicit readiness condition for the page or target element, and wait for lazy content or application state that matters to your capture.

Can Selenium screenshot a page that requires login?

Yes, if your script successfully authenticates and the session can access the page. Handle credentials securely and avoid writing sensitive page content to shared artifact storage.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.