Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
browser automation

Selenium Code to Capture a Screenshot in Python (Files, Bytes, Elements, and Full Pages)

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.

The shortest way to save the current Selenium browser window as a PNG is:

from selenium import webdriver

driver = webdriver.Chrome()
driver.get("https://example.com")
ok = driver.save_screenshot("screenshot.png")
print(ok)  # True when the PNG was written; False on an I/O error
driver.quit()

Call save_screenshot() after the page has reached the state you want to document. Use a filename ending in .png, preferably an absolute or otherwise known-writable path, and check the returned Boolean before treating the capture as successful.

What Selenium captures

Selenium’s standard Python screenshot methods capture the current browser window—the viewport currently rendered by the driver. They do not automatically mean the entire, scrollable document. The right method depends on the scope and form you need:

Need Method Result Portability
Current window saved directly driver.save_screenshot(path) PNG file; returns True or False Common WebDriver method
Current window under alternate name driver.get_screenshot_as_file(path) PNG file; returns a Boolean Common Python API
Current window for your own processing driver.get_screenshot_as_png() Binary PNG bytes Common Python API
Current window for HTML or text transport driver.get_screenshot_as_base64() Base64-encoded PNG Common Python API
One component element.screenshot(path) PNG file for that element Common Selenium element API
Entire document Driver-specific full-page method Usually a PNG file Not identical across drivers

The Python implementation of save_screenshot delegates to get_screenshot_as_file. The file method obtains PNG data, opens the destination in binary mode, writes it, and returns False if an OSError occurs.

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

Save the current window to a PNG

Minimal runnable example

from selenium import webdriver

 driver = webdriver.Chrome()
 driver.get("https://example.com")
 ok = driver.save_screenshot("screenshot.png")
 print(ok)  # True when the PNG was written; False on an I/O error
 driver.quit()

The spacing above is shown exactly as a compact example; in normal Python style, remove the extra leading spaces before the statements inside the script:

from selenium import webdriver

driver = webdriver.Chrome()
driver.get("https://example.com")
ok = driver.save_screenshot("screenshot.png")
print(ok)
driver.quit()

Use a full path when a test runner’s working directory is uncertain:

from pathlib import Path
from selenium import webdriver

output = Path("artifacts")
output.mkdir(parents=True, exist_ok=True)
path = output / "homepage.png"

driver = webdriver.Chrome()
try:
    driver.get("https://example.com")
    if not driver.save_screenshot(str(path)):
        raise OSError(f"Selenium could not write {path}")
finally:
    driver.quit()

The destination directory must exist and be writable. A successful browser capture can still fail at the filesystem step, which is why checking the return value matters.

Choose the output form

Use the alternate file method

ok = driver.get_screenshot_as_file("artifacts/homepage.png")

In the current Python implementation this is functionally equivalent to save_screenshot. It is useful when a codebase already uses the longer WebDriver method name.

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

Keep PNG bytes in memory

png_bytes = driver.get_screenshot_as_png()
with open("screenshot.png", "wb") as image_file:
    image_file.write(png_bytes)

This avoids asking Selenium to choose your storage path. You can send the bytes to an object store, attach them to a test report, or run image processing before writing them.

Embed a Base64 image in HTML

base64_image = driver.get_screenshot_as_base64()
html = f'<img src="data:image/png;base64,{base64_image}">'

Base64 is text rather than a file. It is convenient for self-contained HTML reports, but the resulting string is larger than the underlying binary PNG and should not replace a file or object-store workflow when screenshots are numerous.

Capture one element instead of the whole viewport

Locate the component and call its screenshot method:

from selenium import webdriver

 driver = webdriver.Chrome()
 driver.get("https://example.com")
 element = driver.find_element("css selector", "#checkout")
 element.screenshot("checkout.png")
 driver.quit()

As with a window capture, wait until the element is present and visually ready. A selector that matches nothing raises a lookup exception; a hidden, detached, or still-changing element can produce an unusable result. Element capture is the appropriate scope for a card, form, chart, or other component when browser chrome and unrelated content are not wanted.

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

Full-page screenshots: know the driver boundary

The basic methods document the current window. A long page may therefore be captured only at the current viewport rather than as one image of the whole document. Firefox’s driver API separately documents get_full_page_screenshot_as_file(), for example:

driver.get_full_page_screenshot_as_file("/Screenshots/page.png")

That capability is driver-specific; do not assume the same call or identical behavior exists for every browser. If full-document output is a requirement, select a driver that documents the capability you need and verify the resulting dimensions in your own environment. Otherwise, capture a deliberate viewport or use a service that offers full-page rendering.

Make the page ready before you capture

Selenium takes the screenshot of the state that exists at the instant of the call. A reliable sequence is:

  1. Start the driver with the browser and options used by your test.
  2. Navigate with driver.get(url).
  3. Wait for the content, selector, animation, or network condition your scenario requires.
  4. Set the window size or device emulation before capture if layout matters.
  5. Call the appropriate window or element method.
  6. Check the file Boolean when writing directly to disk.
  7. Close the driver in a finally block so failures do not leave browser processes behind.

Do not use a fixed sleep as a substitute for a condition when page timing varies. A screenshot can be technically valid while showing a loading skeleton, a consent dialog, or an animation frame that is not the state you intended to test. Selenium’s screenshot API does not itself dismiss overlays or wait for application-specific readiness.

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

Common failures and fixes

The method returns False

  • Cause: The destination directory does not exist, the path is relative to an unexpected working directory, or the process lacks write permission.
  • Fix: Create the directory, use an absolute path, confirm permissions, and check the Boolean return.

A file is created but the page is incomplete

  • Cause: Capture ran before the relevant content, images, or client-side rendering finished.
  • Fix: Wait for a specific element or application condition before calling the screenshot method. Capture after any required interaction.

The screenshot shows a cookie banner, popup, or chat widget

  • Cause: Selenium reproduces the browser state; it does not automatically accept consent or remove overlays.
  • Fix: Locate and interact with the banner, hide a known selector for test purposes, or use a capture service with explicit cleanup controls.

The element screenshot raises a lookup or state error

  • Cause: The CSS selector is wrong, the element has not appeared, or the element was replaced by a re-render.
  • Fix: Wait for the selector, locate it immediately before capture, and ensure it is displayed and attached to the current document.

Full-page output is unavailable

  • Cause: Full-document capture is not a universal WebDriver behavior.
  • Fix: Use the full-page method documented for your selected driver, or capture a controlled viewport instead.

The script leaves browser processes running

  • Cause: An exception occurred before quit().
  • Fix: Put navigation and capture inside try and call driver.quit() in finally.

Performance, reliability, and artifact handling

PNG capture returns lossless data and is the API’s documented screenshot format. For repeatable visual tests, keep the viewport, browser, device scale, fonts, data, and page state consistent; otherwise differences may come from rendering conditions rather than the code under test.

Use deterministic filenames that include a test or page identifier, and write artifacts to a run-specific directory. In CI, preserve that directory even when an assertion fails. The in-memory and Base64 methods let you attach the same capture to a report without reading it back from disk.

Remember that a successful screenshot says the driver produced image data, not that the page passed your functional checks. Keep screenshot capture separate from assertions, and record the Boolean file result as an artifact-writing check.

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 for developers. It accepts a URL in one request and returns PNG, JPEG, WebP, or PDF. Before capture it can accept cookie and consent banners and remove more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be switched 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 in X-Page-Verdict and X-Billed headers.

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

For a direct call, see the ScreenshotNeo documentation:

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

The same request in 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)

And in 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}`);

ScreenshotNeo also provides an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. Its options include full-page capture with lazy images loaded, CSS-selector element capture, dark mode, 12 device presets or custom viewports, retina scale, PDF paper settings and page ranges, custom CSS and JavaScript, click-before-capture, selector hiding, waits for a selector, delay or network idle, request and resource blocking, custom headers, cookies, user agent and Authorization, timezone and geolocation, transparent backgrounds, resizing, configurable-TTL caching, signed image links, asynchronous jobs with signed webhooks, bulk capture for up to 100 URLs per call, a usage API, and an OpenAPI specification. Common parameter names used by other screenshot APIs also work.

The Free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 screenshots; every feature is available on every plan. Create a free ScreenshotNeo account to get started.

Frequently Asked Questions

Does Selenium save screenshots as JPEG or WebP?

The documented Python screenshot methods save or return PNG data. Convert the PNG afterward if another image format is required.

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

Can I call save_screenshot before driver.get()?

You can call it only after a driver exists, but a useful page image requires navigating to and preparing the target content first.

What does a True return value mean?

For the file-saving methods, True means Selenium completed the file write without the documented I/O error; it does not validate the page’s visual or functional correctness.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Free tools Windows power users keep installed

One-click scans. No signup required.

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

Read next

Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.