October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
Python

How to Save a Screenshot to a File With Selenium’s get_screenshot_as_file

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

Use driver.get_screenshot_as_file("path/to/file.png") after the page is in the state you want to capture. Selenium writes the current WebDriver window as a PNG and returns True when the write succeeds or False when an I/O error prevents it. Create the parent directory first, use a .png filename, and check that Boolean result instead of assuming a file was created.

Minimal working example

This complete Python example creates its output directory, opens a page, saves the current browser window, and fails loudly if Selenium cannot write the image:

from pathlib import Path
from selenium import webdriver

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

with webdriver.Chrome() as driver:
    driver.get("https://example.com")
    ok = driver.get_screenshot_as_file(str(out / "example.png"))
    if not ok:
        raise OSError("Selenium could not write the screenshot")

get_screenshot_as_file() expects a filename (a string is the most portable choice), writes PNG data, and returns a Boolean. The method captures the window currently controlled by WebDriver; it does not automatically wait for images, JavaScript, animations, or network requests to finish.

What the method actually does

  1. WebDriver obtains PNG bytes for the current window.
  2. Selenium opens the supplied path in binary-write mode.
  3. It writes the bytes and returns True.
  4. If the operating system raises an OSError while opening or writing the file, Selenium catches it and returns False.

That contract makes the return value part of your error handling. A call that raises no Python exception can still report a failed write through False. The documented filename contract is PNG, so end the name in .png; Selenium warns when another suffix is used even if your operating system permits it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB
  • CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
  • WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
  • A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents

Choosing and preparing the destination path

Relative paths

driver.get_screenshot_as_file("screenshots/home.png")

A relative path is resolved from the process’s current working directory, which may differ between a terminal, an IDE, and a CI runner. The screenshots directory must already exist.

Absolute paths

driver.get_screenshot_as_file("/var/tmp/selenium/home.png")

Absolute paths remove ambiguity, especially in test runners. The process still needs write permission for the directory and every parent component.

Portable path construction

from pathlib import Path

filename = Path("artifacts") / "failure.png"
filename.parent.mkdir(parents=True, exist_ok=True)
if not driver.get_screenshot_as_file(str(filename)):
    raise OSError(f"Unable to write {filename}")

Path handles separators on Windows, macOS, and Linux. Convert it with str() when calling Selenium so the code works with Selenium versions that document a string filename.

Unique names in tests

from datetime import datetime, timezone

stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
path = Path("artifacts") / f"checkout-{stamp}.png"
path.parent.mkdir(parents=True, exist_ok=True)
if not driver.get_screenshot_as_file(str(path)):
    raise OSError("Screenshot write failed")

Use a test name, browser name, or run identifier as well when parallel workers can write at the same time. Otherwise workers may overwrite one another’s evidence.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB
  • CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
  • SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors

Capture the right page state

The image is taken at the instant the method runs. Navigate first, then wait for the condition that defines a valid capture rather than relying on a fixed sleep.

Wait for a visible element

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

with webdriver.Chrome() as driver:
    driver.get("https://example.com/dashboard")
    WebDriverWait(driver, 20).until(
        EC.visibility_of_element_located((By.CSS_SELECTOR, "main.dashboard"))
    )
    if not driver.get_screenshot_as_file("artifacts/dashboard.png"):
        raise OSError("Screenshot write failed")

Wait for a test-specific state

WebDriverWait(driver, 20).until(
    lambda d: d.find_element(By.ID, "status").text == "Complete"
)
if not driver.get_screenshot_as_file("artifacts/complete.png"):
    raise OSError("Screenshot write failed")

For pages with lazy-loaded content, scroll or trigger the application behavior that loads the content before capturing. If an animation is still running, wait for a stable class, text value, or other deterministic signal. A screenshot cannot correct a timing mistake after the file is written.

Current-window scope versus full-page screenshots

The method is documented as saving the current window. In ordinary browser sessions that means the viewport rendered by WebDriver, not a guarantee that every pixel of a long, scrollable document appears in one image. Browser implementations expose separate full-page screenshot capabilities; use one of those APIs when a complete document is a requirement and verify that your chosen browser and driver support it.

Do not infer full-page behavior merely because the page has a long body or because the browser’s own developer tools can capture a full page. If you need a reproducible viewport, set its dimensions before navigation:

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.
Rank #3
Sale
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
  • Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
  • Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
  • In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
  • Ultra-thin bezels: Maximize your viewing experience with thin bezels.
with webdriver.Chrome() as driver:
    driver.set_window_size(1440, 1000)
    driver.get("https://example.com")
    if not driver.get_screenshot_as_file("artifacts/viewport.png"):
        raise OSError("Screenshot write failed")

Related Selenium screenshot methods

Method Output Best use Error responsibility
get_screenshot_as_file(filename) PNG file Direct filesystem artifacts Check returned True/False
save_screenshot(filename) PNG file Convenience spelling for the same operation Delegates to get_screenshot_as_file; the same path and Boolean rules apply
get_screenshot_as_png() bytes Upload, hashing, database storage, or custom naming Your code writes or transmits the bytes
get_screenshot_as_base64() Base64 str Embedding in HTML or another text-only transport Your code validates and stores the encoded text

Writing PNG bytes yourself

png_bytes = driver.get_screenshot_as_png()
path = Path("artifacts") / "home.png"
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("wb") as image_file:
    image_file.write(png_bytes)

This alternative is useful when your application already owns storage, encryption, upload retries, or a content-addressed filename. It does not change what Selenium captures.

Embedding a base64 image

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

Base64 increases payload size and is usually less convenient than a file or object-storage URL for large test suites.

Troubleshooting a missing or failed file

The method returns False

  • Missing parent directory: create it with Path(path).parent.mkdir(parents=True, exist_ok=True).
  • Permissions: choose a directory writable by the account running the browser, or correct ownership and permissions. A read-only mount in CI produces the same symptom.
  • Invalid or unavailable absolute path: confirm that the drive, mount, and all parent directories exist inside the environment where the test runs (for example, a container).
  • File collision or lock: generate unique names and close any process that has locked the destination.

Log the resolved path and current working directory before the call. Preserve the Boolean check so a future filesystem change cannot silently remove evidence.

The file exists but has the wrong suffix

Rename it to end in .png. Selenium’s documented output is PNG, and a non-PNG name triggers a warning and can confuse artifact viewers or later tooling.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor
  • CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
  • SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
  • MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
  • KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
  • INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient

The screenshot is blank, stale, or missing content

  • Wait for a navigation or a specific visible element instead of capturing immediately after get().
  • Wait for application data, fonts, images, or a status change that proves rendering is complete.
  • Ensure you are on the intended window or tab; WebDriver captures the currently selected window.
  • Check viewport size and responsive breakpoints. Headless and headed runs can use different defaults.
  • For a long page, use a browser-supported full-page API rather than expecting this current-window method to stitch the document.

The call appears to hang

The file-writing operation itself is small, but page scripts, an unresponsive browser, or a blocked navigation can delay the point at which you call it. Put explicit timeouts around navigation and waits, collect browser and driver logs, and capture only after your readiness condition succeeds.

Operational practices for reliable artifacts

  • Keep capture and assertion separate: take the screenshot in a failure handler, but check its return value and report a second error if artifact creation fails.
  • Use deterministic directories: write to a run-specific directory and publish that directory as a CI artifact.
  • Record context: include URL, viewport, browser, test name, and timestamp in adjacent metadata or the filename.
  • Control disk usage: retain only the runs your debugging or compliance policy requires; PNG files can become substantial at high viewport sizes.
  • Protect sensitive data: screenshots may contain account details, tokens displayed by a test page, or personal information. Restrict artifact access and scrub data before sharing.
  • Do not treat a screenshot as a page-health check: a successful file write proves that bytes were saved, not that the page’s business logic is correct.
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 your goal is a clean website image rather than browser-driving code, ScreenshotNeo provides a single HTTP request. Before capture it accepts cookie or consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing result.

Read the parameter reference in the ScreenshotNeo documentation. The API returns PNG, JPEG, WebP, or PDF and also supports full-page capture, CSS-selector elements, device presets, custom viewports, retina scale, waits, custom CSS and JavaScript, clicks, hidden selectors, blocked resources, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, selectable cache TTLs, signed links, asynchronous webhooks, bulk capture of up to 100 URLs per call, a usage API, and an OpenAPI specification.

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

ScreenshotNeo includes an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. The Free plan includes 1,000 shots each month with no card; paid plans start at $5 for 3,000 shots, and every feature is available on every plan. Create a free ScreenshotNeo account.

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.

FAQ

Can I pass a pathlib.Path directly?

Convert it with str(path) for compatibility with Selenium versions that specify a string filename.

Best Value
Sale
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
  • 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
  • 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.

Does a successful return value prove the screenshot is correct?

No. True means the PNG bytes were written successfully. It does not validate page content, timing, viewport choice, or test assertions.

When should I choose in-memory PNG bytes?

Use get_screenshot_as_png() when storage, upload, hashing, or naming is controlled by your application rather than by Selenium’s direct file write.

Why is a full-page screenshot a separate decision?

get_screenshot_as_file() targets the current window. Complete-document capture depends on browser-specific full-page support, so select and test that API explicitly.

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

Frequently Asked Questions

Can I pass a pathlib.Path directly?

Convert it with str(path) for compatibility with Selenium versions that specify a string filename.

Does a successful return value prove the screenshot is correct?

No. True means the PNG bytes were written successfully; it does not validate page content, timing, viewport choice, or test assertions.

When should I choose in-memory PNG bytes?

Use get_screenshot_as_png() when your application controls storage, upload, hashing, or naming.

Why is a full-page screenshot a separate decision?

get_screenshot_as_file() targets the current window; complete-document capture depends on browser-specific full-page support.

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.

Leave a Reply

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

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

Read next

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

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.