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

In a Python Selenium test, save the current browser view with driver.save_screenshot('path/to/file.png'). Create the destination directory first, use a .png filename, and check the returned boolean so an I/O failure cannot pass unnoticed. Capture a single DOM element with element.screenshot(...), or keep the image in memory with get_screenshot_as_png() or get_screenshot_as_base64().

The examples below follow the Selenium Python WebDriver API surfaced as version 4.49.0. Method names and surrounding test-runner code can change between Selenium releases, so verify the API version installed in your environment.

Quick answer: save a window screenshot

This is a complete minimal example. It opens a browser, creates the artifact directory, captures the current window, and fails explicitly if Selenium cannot write the file.

from pathlib import Path
from selenium import webdriver

output_dir = Path('artifacts/screenshots')
output_dir.mkdir(parents=True, exist_ok=True)

with webdriver.Chrome() as driver:
    driver.get('https://example.com')
    path = output_dir / 'example-page.png'
    saved = driver.save_screenshot(str(path))
    if not saved:
        raise OSError(f'Selenium could not save the screenshot to {path}')

save_screenshot writes a PNG and returns True on success or False when Selenium encounters an I/O error. It does not return image bytes. The directory creation is ordinary Python filesystem handling; Selenium does not create missing parent directories for you.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Choose what evidence to capture

The complete visible browser window

Use driver.save_screenshot(path) when the failure context spans several controls, when you need to see the page state around an error, or when a test records a visual checkpoint. Selenium also exposes driver.get_screenshot_as_file(filename) for the same file-saving purpose and the same boolean success convention.

The screenshot represents the current browser view. Navigate, wait for the state you want, and call the method before teardown closes the driver. A screenshot taken after driver.quit() is impossible because the capture API belongs to the live WebDriver session.

One element

Locate the component and call its screenshot method when the full window would add noise. The element API documents a PNG file and a boolean result.

from pathlib import Path
from selenium import webdriver
from selenium.webdriver.common.by import By

output_dir = Path('artifacts/screenshots')
output_dir.mkdir(parents=True, exist_ok=True)

with webdriver.Chrome() as driver:
    driver.get('https://example.com')
    card = driver.find_element(By.CSS_SELECTOR, "[data-testid='pricing-card']")
    path = output_dir / 'pricing-card.png'
    saved = card.screenshot(str(path))
    if not saved:
        raise OSError(f'Could not save element screenshot to {path}')

If the selector does not match, Selenium raises a lookup exception before the screenshot call. Treat that as a test failure and include the selector in the diagnostic output.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

PNG bytes or Base64 in memory

Use the byte method when another library, an object store client, or a test-report attachment API should receive the image without an intermediate file. Use Base64 when an HTML report expects text.

from selenium import webdriver

with webdriver.Chrome() as driver:
    driver.get('https://example.com')
    png_bytes = driver.get_screenshot_as_png()
    base64_text = driver.get_screenshot_as_base64()

    # Example consumers:
    # report.attach('window.png', png_bytes, 'image/png')
    # html = f"<img src='data:image/png;base64,{base64_text}'>"

get_screenshot_as_png() returns PNG bytes. get_screenshot_as_base64() returns a Base64-encoded string suitable for embedding in HTML. Neither method writes a file or checks whether your report system has retained the data.

Capture at the right point in a test

After the state you want is visible

Place the call after navigation and after the wait that establishes the assertion state. A screenshot taken immediately after get can show a loading page rather than the component under test. Use your normal explicit wait for a selector, visibility, or application condition; screenshot capture itself is not a synchronization mechanism.

Only when a test fails

Capturing every step produces more files and can slow a large suite. A common pattern is to capture in an exception path, name the file with test and run context, then re-raise the original failure. The test framework and CI system determine how to hook this into teardown and how to publish artifacts; Selenium does not prescribe a pytest hook, retention period, or upload service.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
from pathlib import Path
from datetime import datetime, timezone
from selenium import webdriver


def run_case():
    driver = webdriver.Chrome()
    try:
        driver.get('https://example.com')
        # Perform actions and assertions while driver is alive.
        assert 'Example' in driver.title
    except Exception:
        stamp = datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')
        output_dir = Path('artifacts/screenshots')
        output_dir.mkdir(parents=True, exist_ok=True)
        path = output_dir / f'run_case-{stamp}.png'
        if not driver.save_screenshot(str(path)):
            raise OSError(f'Could not save failure screenshot to {path}')
        raise
    finally:
        driver.quit()


run_case()

This example deliberately keeps the driver open while the exception is handled. In a real suite, put equivalent logic in the framework’s failure hook and pass the active driver to it. If teardown quits the browser first, no driver-bound screenshot can be obtained afterward.

Every test versus failure-only

Policy Useful when Trade-off
Every test or checkpoint You need a visual history of successful states, visual-regression input, or debugging for a new flow. More disk usage, uploads, and processing.
Failure only The suite is stable and screenshots are primarily diagnostic evidence. A transient problem may disappear before a rerun, so the first failure is the only captured state.

Make paths and names reliable

  • Create the directory before calling Selenium, including in clean CI workspaces.
  • Use an absolute path when the test runner can change the process working directory. Selenium’s API recommends a full path and a .png extension.
  • Include test name, browser, shard, retry, and a timestamp or unique run ID so parallel workers do not overwrite one another.
  • Keep screenshots in the directory your CI job is configured to preserve. Writing a local file does not automatically upload it or guarantee retention on a remote worker.
  • Check the boolean returned by save_screenshot or get_screenshot_as_file. If it is False, report the path and keep the original test failure visible.

For in-memory captures, apply the same ownership rule: the report or storage client must consume the bytes before the test process exits.

Control framing without assuming identical pixels

Set a window size when a predictable viewport is important:

from selenium import webdriver

with webdriver.Chrome() as driver:
    driver.set_window_size(1366, 900)
    driver.get('https://example.com')
    if not driver.save_screenshot('artifacts/screenshots/1366x900.png'):
        raise OSError('Screenshot write failed')

set_window_size(width, height) uses pixel dimensions. It helps control the requested frame, but the Selenium API does not promise pixel-identical rendering across browsers, operating systems, fonts, graphics stacks, or headless environments. Treat it as a reproducibility aid, not a cross-machine visual guarantee. Keep browser version, operating system, fonts, viewport, device scale, and page data consistent when comparing images.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

Diagnose common failures

Symptom Likely cause Fix
False from the file method The path is unwritable, a parent directory is missing, or the process received an operating-system I/O error. Create the directory, use a writable absolute path, check permissions, and fail with the returned status instead of assuming the file exists.
No file appears in CI The file was written on a worker that was discarded, or the artifact upload step did not include its directory. Write to the runner’s documented artifact directory and configure retention/upload in the CI system. This is outside Selenium’s API.
Screenshot shows the wrong page state The call ran before navigation, animation, or an asynchronous component finished. Wait for the application condition you need, then capture. Do not use a fixed sleep as a substitute when an explicit condition is available.
Element screenshot raises a lookup error The locator is wrong, the element is inside a frame not selected, or the DOM changed. Select the correct frame first, wait for the element, and include the locator and current URL in failure diagnostics.
Capture fails after an assertion Exception handling runs after teardown has already called quit. Move capture into the failure path while the driver is still alive; postpone quitting until after the attempt.
Images differ between machines Different browser/OS/font/headless settings or dynamic page content. Pin the environment where practical, set the viewport, disable or control changing data, and interpret dimensions as an aim rather than a guarantee.
Report attachment is empty Bytes or Base64 were requested but never passed to the report before the test ended. Attach the returned bytes or embed the returned Base64 string immediately, and verify the report tool’s MIME type.

Window, element, file, or memory: a practical decision table

Need Call Output
Context across the visible page driver.save_screenshot(path) PNG file; boolean success result
Same file behavior through the alternate API driver.get_screenshot_as_file(filename) PNG file; boolean success result
Only one component element.screenshot(path) PNG file; boolean success result
Attach without filesystem I/O driver.get_screenshot_as_png() PNG bytes
Embed in an HTML report driver.get_screenshot_as_base64() Base64 text

These choices are independent of whether you capture on every test or only on failure. The latter policy and artifact retention belong to your test framework and CI configuration.

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

Language-binding differences

Selenium’s official multi-language examples show that the storage step differs by binding. Python uses the methods above; Java uses TakesScreenshot and a file copy; C# uses GetScreenshot().SaveAsFile(...); JavaScript uses driver.takeScreenshot() and receives an encoded string. Do not paste a Python method name into another binding: check that binding’s current API and handle its returned data or file explicitly.

Or skip the browser setup

If you need a URL image or PDF rather than evidence tied to an already-running Selenium session, ScreenshotNeo is a website screenshot API and MCP server. It accepts a URL in one GET request and returns PNG, JPEG, WebP, or PDF. Before capture it can accept the cookie or consent banner like a visitor and remove more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be switched off. Only clean shots are billed: bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and response headers identify the page verdict and billing result.

For a single call, see the ScreenshotNeo API documentation:

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.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com -o shot.webp

The equivalent Python request is:

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)

Node.js:

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

ScreenshotNeo also supports full-page captures with lazy images loaded, CSS-selector element captures, dark mode, 12 device presets or a custom viewport, retina scale, PDF paper and margin controls, custom CSS and JavaScript, clicks before capture, selector hiding, waits for a selector, delay, or network idle, request and resource blocking, custom headers, cookies, user agents and Authorization, timezone and geolocation, transparent backgrounds, resizing, chosen cache TTLs, signed links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, a usage API, and an OpenAPI specification. Parameter names used by other screenshot APIs also work, which can simplify a switch.

Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

An MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. Plans include 1,000 shots per month free with no card; paid plans start at $5 for 3,000 shots. Sign up for the free ScreenshotNeo plan to try the one-call workflow.

Frequently Asked Questions

Can I attach both a full-window and an element image from one test?

Yes. Locate the element and call its screenshot method in addition to the window method while the same WebDriver session remains open; use distinct filenames so the artifacts are not overwritten.

What should an HTML report use instead of a temporary PNG file?

Call get_screenshot_as_base64() and place the returned text in an image data URI, or call get_screenshot_as_png() and pass the bytes to the report API. The report system still controls attachment size and retention.

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

Will setting the same window size make screenshots pixel-identical everywhere?

No. It controls requested pixel dimensions, but browser, operating-system, font, graphics, headless, and page-data differences can still change rendered pixels.

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.