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

Call driver.get_screenshot_as_file() after the page reaches the state you want to capture, pass a writable path ending in .png, and check the Boolean result. Create the parent directory yourself—Selenium does not create it.

Save a Selenium screenshot in one checked call

This complete Python example creates the destination directory, opens a page, saves the current WebDriver window as a PNG, and treats a failed write as an error:

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')

The resulting file is screenshots/example.png, relative to the process working directory. Use an absolute path when a test runner, container, or CI job may start in an unexpected directory.

What get_screenshot_as_file does

Selenium’s API defines get_screenshot_as_file(filename) as saving a screenshot of the current WebDriver window to a PNG image file. The filename should end in .png; Selenium warns for another suffix because PNG is the documented output format.

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.
#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

The filename is a filesystem path

Both relative and absolute paths work:

driver.get_screenshot_as_file('screenshots/home.png')
driver.get_screenshot_as_file('/var/tmp/selenium/home.png')

When using pathlib.Path, convert it with str(path). This makes the value explicitly compatible with WebDriver implementations that expect a string.

The return value is part of the contract

The method returns True after the PNG bytes have been written and False when an I/O error prevents the write. A failed write is reported through that Boolean, so do not assume that the absence of a Python exception means a file exists.

if not driver.get_screenshot_as_file('artifacts/failure.png'):
    print('Screenshot write failed')

Selenium’s implementation obtains the PNG bytes, opens the supplied filename in binary-write mode, writes the bytes, catches OSError, and returns the corresponding Boolean.

Prepare the path before calling Selenium

Create every parent directory

Selenium will not create screenshots, artifacts, or any other missing parent directory. Create it before the call:

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.
from pathlib import Path

file_path = Path('artifacts') / 'run-42' / 'home.png'
file_path.parent.mkdir(parents=True, exist_ok=True)

if not driver.get_screenshot_as_file(str(file_path)):
    raise OSError(f'Could not write {file_path}') 

Use a writable location

A read-only directory, a protected absolute path, or a process running as a user without write permission causes the operating system open/write operation to fail and produces False. In containers and CI, verify the mounted artifact directory and its permissions rather than relying on a developer’s local path.

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

Prefer deterministic, unique names

Include a test name, URL slug, or run identifier in the filename when several captures are produced. This prevents unrelated steps from targeting the same path and makes failed artifacts easier to locate:

name = f'checkout-{run_id}-after-submit.png'
target = Path('screenshots') / name
target.parent.mkdir(parents=True, exist_ok=True)
if not driver.get_screenshot_as_file(str(target)):
    raise OSError('Screenshot file was not written')

Capture the right browser state

Navigate first, then wait for the state you need

The screenshot reflects the window at the instant the method runs. driver.get() returning does not necessarily mean that client-side rendering, an image, or a test-specific element is ready. Wait for the condition that matters to your capture before saving.

from selenium.webdriver.support.ui import WebDriverWait

with webdriver.Chrome() as driver:
    driver.get('https://example.com/dashboard')
    WebDriverWait(driver, 20).until(
        lambda d: d.execute_script('return document.readyState') == 'complete'
    )
    WebDriverWait(driver, 20).until(
        lambda d: d.find_element('css selector', '[data-page-ready]')
    )
    if not driver.get_screenshot_as_file('/var/tmp/dashboard.png'):
        raise OSError('Screenshot write failed')

For a particular visual state, wait for that state—not merely for navigation. For example, wait until a loading element disappears or a result element is present before taking the screenshot.

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

Understand the capture scope

This method captures the current WebDriver window. It is not a promise to capture every pixel of a long, scrollable document. If you require a full-document image, use a separate full-page screenshot API supported by the browser implementation you are running and verify its behavior for that browser.

Control the active window and viewport

The current window and its current viewport determine what is captured. If your test opens a second tab or window, switch to the intended handle before saving. Set the window size or device emulation before navigation when a reproducible layout matters.

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.

Related Selenium screenshot methods

Method Output Scope or handling
get_screenshot_as_file(path) PNG file Writes the current window; returns True or False.
save_screenshot(path) PNG file Convenience method that delegates to get_screenshot_as_file, so the same path, PNG, and return-value rules apply.
get_screenshot_as_png() PNG bytes Use when your application will upload, hash, transform, or store the bytes itself.
get_screenshot_as_base64() Base64 str Use for HTML embedding or another text-only transport.

Write bytes yourself when storage is custom

The in-memory method gives your code control over storage and naming:

png_bytes = driver.get_screenshot_as_png()
with open('screenshots/home.png', 'wb') as f:
    f.write(png_bytes)

encoded = driver.get_screenshot_as_base64()

With this approach, your application owns file handling and must report or handle its own write errors. The bytes are still a PNG representation of the current window.

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

Troubleshoot failed or unexpected files

Symptom Likely cause Fix
The method returns False. Missing directory, insufficient permission, invalid path, or another operating-system I/O error. Create the parent directory, use a writable location, use a valid filename, and log the absolute path. Check the Boolean and raise an error.
No file appears for screenshots/home.png. The relative path is resolved from the process working directory, or the parent directory does not exist. Print Path.cwd(), create the directory with mkdir(parents=True, exist_ok=True), or pass an absolute path.
A warning mentions the filename extension. The name does not end in .png. Use the documented .png suffix; do not rely on an operating system accepting another suffix.
The file exists but shows an earlier or incomplete page. The call ran before navigation, rendering, or the required test state finished. Wait for the specific element or state you need, then capture.
The image contains only the visible portion of a long page. get_screenshot_as_file captures the current window rather than guaranteeing a full scrollable document. Use a browser-specific full-page screenshot API when full-document output is required.
The screenshot is from the wrong tab. WebDriver is focused on another window handle. Switch to the intended window before calling the method.
A test intermittently fails on the write. Several workers use the same path, or the destination is a transient or unwritable mount. Generate unique names per worker/run and write to a known writable artifact directory.

Reliability and performance considerations

Keep waits separate from file handling

Waiting determines what is photographed; the screenshot method only writes the current result. Keeping those concerns separate makes failures diagnosable: a timeout is a page-state problem, while False is a file-write problem.

Use PNG deliberately

The API contract is PNG. PNG preserves text and interface edges well, but large viewport sizes and image-heavy pages produce larger files and consume more memory during capture. Choose a practical viewport and avoid taking repeated captures when one artifact answers the debugging question.

Make artifact handling observable

Log the resolved destination, the active test or run identifier, and the returned Boolean. In CI, publish the directory as an artifact only after verifying the file was written. For in-memory workflows, check that your own storage or upload operation completed because Selenium cannot report errors in a downstream system.

Rank #4
Sale
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

Or skip the browser setup

If you need a URL rendered to an image or PDF without managing a local browser, ScreenshotNeo provides a website screenshot API and MCP server. One GET request returns PNG, JPEG, WebP, or PDF. It accepts cookie and consent banners like a visitor, then removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled.

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

Here is the one-call cURL example (the API documentation is at https://screenshotneo.com/docs/):

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 reports page and billing outcomes in X-Page-Verdict and X-Billed headers. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed; only clean shots are billed. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.

For more control, the service supports full-page capture with lazy images loaded, CSS-selector element capture, dark mode, 12 device presets or any viewport, retina scale, PDF paper size/margins/landscape/page ranges, HTML/CSS rendering, custom CSS and JavaScript, pre-capture clicks, hidden selectors, selector/delay/network-idle waits, ad/tracker/request/resource blocking, custom headers/cookies/user agent/Authorization, timezone and geolocation, transparent backgrounds, image resizing, selectable cache TTL, signed links for public image tags, asynchronous jobs with signed webhooks, bulk capture of 100 URLs per call, a usage API, and an OpenAPI specification. Parameter names used by other screenshot APIs also work for easier migration.

Plan Included shots Price
Free 1,000 per month $0, no card
Starter 3,000 $5
Growth 15,000 $15
Pro 60,000 $39
Scale 250,000 $99
Business 1,000,000 $249

Every feature is available on every plan, and yearly billing gives two months free. You can start with 1,000 free screenshots a month with no card; paid plans start at $5 for 3,000 shots.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

FAQ

Can I pass a pathlib.Path directly?

Convert it to a string with str(path) when calling the method. This makes the filename argument explicit and portable across WebDriver implementations.

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 True result prove that the page was correct?

No. It confirms that Selenium wrote the PNG file successfully. Your waits and assertions still determine whether the captured browser state was the one your test intended.

When should I use a full-page API instead?

Use one when the requirement is the entire scrollable document rather than the current WebDriver window. Full-page support is browser-specific and separate from this file-saving method.

Frequently Asked Questions

Can I pass a pathlib.Path directly?

Convert it with str(path) when calling get_screenshot_as_file so the filename argument is an explicit string.

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

Does a True result prove that the page was correct?

No. True confirms that Selenium wrote the PNG file; your waits and assertions must establish that the captured browser state was the intended one.

When should I use a full-page API instead?

Use a browser-specific full-page screenshot API when you need the entire scrollable document rather than the current WebDriver window.

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.