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

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

Use Selenium’s WebDriver method browser.save_screenshot("page.png") to write a PNG of the browser’s current window. The method returns True when the file is saved and False when an I/O error prevents the save. Create a writable destination first, use a .png filename, and check the return value when a failed capture must stop your program.

What browser.save_screenshot() captures

save_screenshot(filename) is part of Selenium WebDriver’s Python API. Despite the variable name in this article, browser is simply your WebDriver object; Selenium examples often call the same object driver. The method saves the current browser window as a PNG image file. Selenium’s API description calls this “the current window,” so do not treat it as a built-in full-page, entire-document capture.

The filename should end in .png. Selenium documents a filename-based save and a boolean result: False indicates an IOError; otherwise the method returns True. The Selenium API reference is at selenium.webdriver.remote.webdriver.

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

Complete Selenium example

This runnable script creates its output directory, opens a page, saves the current window, checks the result, and closes the browser even when an exception occurs.

from pathlib import Path
from selenium import webdriver

out = Path("screenshots")
out.mkdir(parents=True, exist_ok=True)

browser = webdriver.Chrome()
try:
    browser.get("https://example.com")

    saved = browser.save_screenshot(str(out / "page.png"))
    if not saved:
        raise RuntimeError("Screenshot save failed")

    print("Saved", out / "page.png")
finally:
    browser.quit()

Install Selenium with pip install selenium and ensure a compatible browser (such as Chrome) is available. Recent Selenium releases can manage the browser driver in common setups; if your environment requires a separately managed driver, configure it according to your browser and Selenium installation.

Path, filename and return-value rules

Use a real, writable path

The parent directory must exist and the process must have permission to write it. The example uses Path.mkdir(..., exist_ok=True) so a fresh checkout does not fail merely because screenshots is absent. A relative path is resolved from Python’s process working directory; use an absolute path when a service, test runner or container has an uncertain working directory. Selenium’s API guidance recommends full paths, while its own example also demonstrates a relative path.

Keep the PNG extension

Pass a name such as page.png or /tmp/run-42.png. The documented method is a PNG file save. Do not rename a JPEG or WebP expectation onto this method.

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.

Handle False

Do not assume that returning from the call proves the artifact exists. Test the boolean result and raise, retry, or report an error as appropriate for your job. A successful return means Selenium did not encounter the documented I/O failure; your pipeline can still verify the file if it needs stronger delivery guarantees.

Timing: capture the state you actually want

Selenium captures the page state at the moment you call the method. Navigate first, then wait for the condition that defines a ready page before saving. For a deterministic test, wait for a specific element rather than relying on an arbitrary sleep.

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait

browser.get("https://example.com/dashboard")
WebDriverWait(browser, 20).until(
    lambda b: b.find_element(By.CSS_SELECTOR, "main.dashboard")
)
if not browser.save_screenshot("dashboard.png"):
    raise RuntimeError("Could not write dashboard.png")

Make sure the desired tab or window is selected before calling the method. If your application opens a new window, switch to its handle first; otherwise Selenium will capture whichever window is currently active.

Viewport screenshot versus full-page capture

save_screenshot() is documented for the current window. In practical terms, it is the visible browser-window capture provided by Selenium, not an API that promises the complete scrollable document in one image. Long pages, content below the viewport, and lazy-loaded sections therefore need a different approach if they must all appear in one file.

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

Playwright Python exposes a separate screenshot API. Its screenshots documentation shows page.screenshot(path="screenshot.png"), full_page=True for the full scrollable page, and a bytes result when path is omitted. It also documents element screenshots. Choose that scope explicitly instead of assuming Selenium’s method has the same option.

When you need bytes or base64 instead of a file

Selenium also provides methods for consumers that do not want an immediate filesystem write:

  • browser.get_screenshot_as_png() returns PNG image bytes. You can send those bytes to object storage, attach them to a test report, or process them in memory.
  • browser.get_screenshot_as_base64() returns a base64-encoded string, useful when an API or document expects base64 rather than binary data.
png_bytes = browser.get_screenshot_as_png()
with open("page-from-bytes.png", "wb") as image_file:
    image_file.write(png_bytes)

encoded = browser.get_screenshot_as_base64()
print(encoded[:32], "...")

These methods avoid the boolean file-save path, so handle storage, encoding and downstream errors yourself.

Headless and automated runs

The save call is the same in headed and headless Selenium sessions. Headless execution is useful in CI, but the browser’s configured window size determines the captured viewport. Set a deliberate size when responsive layout matters:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_argument("--headless")
options.add_argument("--window-size=1440,900")
browser = webdriver.Chrome(options=options)

Use a virtual display or a headed session when your environment requires one. A screenshot showing a mobile layout, a desktop layout, or a clipped component may simply reflect the configured viewport, not a failed save.

Common failures and fixes

False is returned

  • Check that the parent directory exists.
  • Check write permissions for the account running Python.
  • Use a valid filename ending in .png.
  • Use an absolute path in CI or a service with an unknown working directory.
  • Log the resolved path and retry only after correcting the underlying I/O condition.

FileNotFoundError or a missing directory

Create the directory before capture, as in out.mkdir(parents=True, exist_ok=True). A relative directory is created beneath the process working directory, which may differ between your terminal and test runner.

The image is blank, incomplete or still loading

Wait for a meaningful selector, text condition or other application-ready signal before saving. A navigation call can finish while client-side rendering, fonts or images are still pending. For lazy content, scroll or use a capture tool that explicitly supports full-page loading.

The wrong tab or page is captured

Inspect browser.current_url and switch to the intended window handle before the call. Selenium captures the currently selected window.

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

The result is not a whole page

This is a scope mismatch, not necessarily an error. Selenium documents the method for the current window. Use Playwright’s full_page=True when a full scrollable-page image is a requirement, or capture and stitch sections in your own workflow.

Driver or browser startup fails

Resolve the browser/driver installation and version issue first; save_screenshot() cannot run until a WebDriver session exists. Confirm that a minimal webdriver.Chrome() session opens and quits before debugging paths or page timing.

Choosing among Selenium, Playwright and Robot Framework

Approach Typical scope Output and notable behavior
Selenium WebDriver Python Current window save_screenshot(filename) writes PNG and returns a boolean; PNG bytes and base64 methods are also available.
Playwright Python Page, full scrollable page, or element page.screenshot(path=...); full_page=True enables full-page capture; omitting path returns bytes. See the official guide.
Robot Framework Browser Page or element Powered by Playwright, with screenshot keywords and configurable filename/path behavior. See Browser Library and its keyword reference.
Robot Framework Screenshot library Machine display A separate workflow that can require an installed screenshot tool or module and a physical or virtual display. See its documentation.

These libraries are not interchangeable: a page screenshot, an element screenshot and a machine-display screenshot have different prerequisites and results.

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

Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server. One GET request returns PNG, JPEG, WebP or PDF, without requiring you to install or operate a browser. Its capture options include full-page images with lazy images loaded, CSS-selector element capture, device and viewport settings, retina scale, dark mode, custom CSS and JavaScript, waits, request blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, caching, signed links, asynchronous jobs, bulk capture and PDF controls. Every feature is available on every plan.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo documentation for parameters and response headers. Before capture, it accepts cookie or consent banners and removes more than 60 known consent platforms, newsletter popups and chat widgets; each step can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed, and the response identifies the page verdict and billing status with X-Page-Verdict and X-Billed headers. An MCP server supplies take_screenshot, get_page_info and capture_pdf tools to Claude, Cursor and other MCP clients.

The Free plan includes 1,000 shots per month with no card. Paid plans start at $5 for 3,000 shots; yearly billing provides two months free. Create a free ScreenshotNeo account to try the API.

Python, Node.js and API equivalents

If your workflow is moving from Selenium to a service call, these equivalent examples use the same ScreenshotNeo endpoint:

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.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()));

Use Selenium when you need an interactive browser session under your control. Use an API when repeatable remote capture, cleanup of consent UI, service-side options or agent tooling is more useful than maintaining browser infrastructure.

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

Practical checklist

  • Start a working Selenium WebDriver session.
  • Navigate to the target URL and select the intended window.
  • Wait for the page state that must appear in the image.
  • Create a writable output directory.
  • Pass a PNG filename to save_screenshot().
  • Check the returned boolean and retain the artifact path.
  • Use Playwright or an API when you require full-page, element-specific or service-side capture features.

FAQ

Can I name the WebDriver variable browser?

Yes. The variable name is local to your program; the method is available on any Selenium WebDriver instance.

Does the method save JPEG or WebP?

The documented Selenium method saves a PNG screenshot. Choose another capture API when a different format is a requirement.

How do I embed a Selenium screenshot in another system?

Use get_screenshot_as_png() for binary data or get_screenshot_as_base64() for an encoded string, then pass that value to your report or API client.

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.

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