ScreenshotNeo

BlogHow-to

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

Save Selenium’s current browser window as a PNG, verify the write succeeded, and fix common path, timing, and permissions errors.

By the ScreenshotNeo team29 September 202610 min read

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

To save Selenium’s current browser window as a PNG file, call driver.get_screenshot_as_file(filename) after the page is ready. Create the destination directory first, use a filename ending in .png, and check the method’s Boolean return value: True means the file was written; False indicates an I/O failure. Prefer an absolute path in automation so the output location is predictable.

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 method captures the current WebDriver window, not necessarily the entire scrollable page. Selenium documents the filename as a PNG path, recommends full paths, and defines the return type as a Boolean. See the Selenium Python WebDriver API and the Selenium implementation.

1. Save a screenshot with get_screenshot_as_file

The normal sequence is simple: start a WebDriver session, navigate, wait for the page state you intend to capture, make sure the output directory exists, then save and inspect the result. Selenium obtains PNG bytes from the current window and writes them to the supplied filename. The method catches an operating-system write error and reports it as False.

Selenium captures the current browser window and writes PNG bytes to a path that must already have a writable parent directory.
Selenium captures the current browser window and writes PNG bytes to a path that must already have a writable parent directory.

Minimal example

from selenium import webdriver

with webdriver.Chrome() as driver:
    driver.get("https://example.com")
    saved = driver.get_screenshot_as_file("example.png")
    if not saved:
        raise OSError("Could not save example.png")

This writes example.png relative to the process’s current working directory. That directory may differ between a local terminal, an IDE, a CI runner, and a container. For scripts that must put artifacts in a known place, resolve an absolute path and create its parent directory:

from pathlib import Path
from selenium import webdriver

output = Path("artifacts") / "home.png"
output.parent.mkdir(parents=True, exist_ok=True)

with webdriver.Chrome() as driver:
    driver.get("https://example.com")
    if not driver.get_screenshot_as_file(str(output.resolve())):
        raise OSError(f"Screenshot was not written to {output}")

Passing str(path) makes the filesystem path explicit to Selenium. Python’s Path object is useful for composing paths, but converting it to a string is a portable choice for the WebDriver method.

Why check the return value?

A successful call returns True. If opening or writing the file raises an OSError, Selenium returns False. A caller that ignores the Boolean can finish without a screenshot and without its own code raising an exception. In test infrastructure, fail clearly or record the failed artifact so a missing image is not mistaken for a passing capture.

saved = driver.get_screenshot_as_file("artifacts/failure.png")
if not saved:
    print("Screenshot write failed; check the path and permissions")

2. Choose and prepare the output path

The argument is a filename, including the directory if needed. Selenium does not create missing parent directories. A relative path is interpreted from the Python process’s working directory; an absolute path removes that ambiguity. The destination must also be writable by the user running the browser process.

Path style Example What to account for
Current directory "home.png" Output location depends on the process working directory.
Relative subdirectory "artifacts/home.png" Create artifacts before saving.
Absolute path "/tmp/run-42/home.png" Confirm the directory exists and the process can write there.

Use the .png suffix. The API’s contract is PNG output, and Selenium’s implementation warns when a filename does not end in .png. Renaming the suffix does not convert the image format.

Use a unique path in repeated runs

If every run writes to the same filename, later captures overwrite earlier ones. Use a run identifier, a test name, or a timestamp when preserving multiple artifacts matters. Keep path components controlled when they incorporate test data; unexpected separators can produce a different destination than intended.

from pathlib import Path
from datetime import datetime, timezone

stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
output = Path("artifacts") / f"page-{stamp}.png"
output.parent.mkdir(parents=True, exist_ok=True)

if not driver.get_screenshot_as_file(str(output.resolve())):
    raise OSError(f"Could not write {output}")

3. Wait for the page state you want

The screenshot represents the window at the instant Selenium captures it. Navigation returning does not guarantee that every application-specific image, animation, or asynchronous component is ready. Wait for an observable condition tied to the content of interest rather than adding an arbitrary long delay.

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")
    WebDriverWait(driver, 10).until(
        EC.visibility_of_element_located((By.CSS_SELECTOR, "main"))
    )
    if not driver.get_screenshot_as_file("artifacts/page.png"):
        raise OSError("Screenshot write failed")

Choose a wait condition that matches the requirement: element visibility for a visible component, presence for DOM readiness, or a test-specific condition for an application state. A fixed sleep can be useful when no condition is available, but it adds time to every run and may still be too short on a slow run.

4. Understand the capture scope

get_screenshot_as_file saves a screenshot of the current window. Do not assume it captures every pixel of a long, scrollable document in every browser. If you need the full document, use a full-page screenshot API supported by the specific browser or driver implementation and confirm its behavior for your target environment.

The current-window screenshot and a full-document screenshot are different capture scopes.
The current-window screenshot and a full-document screenshot are different capture scopes.

For a viewport screenshot, set the window size before navigation or capture if reproducible dimensions matter. Browser chrome is not the page content; the screenshot is taken from the WebDriver-controlled browser window. Responsive layouts can change when the viewport changes, so use the same dimensions in local and CI environments when comparing screenshots.

5. Save bytes or Base64 instead of writing a file

Use get_screenshot_as_png() when your application needs the PNG bytes for a custom storage layer, upload, or hash. Use get_screenshot_as_base64() when a text representation is required, such as embedding into HTML. These methods return data to your code; your application then owns any file write and its errors.

from pathlib import Path

png_bytes = driver.get_screenshot_as_png()
Path("artifacts/from-bytes.png").write_bytes(png_bytes)

encoded = driver.get_screenshot_as_base64()
print(f"Base64 characters: {len(encoded)}")

The byte method avoids an intermediate Base64 encoding when the next system accepts binary data. If using either in-memory method for a file, create the directory and handle filesystem exceptions in your own code.

6. The convenience alias: save_screenshot

driver.save_screenshot(filename) is the convenience method for saving the current window. Selenium’s implementation delegates it to get_screenshot_as_file, so the PNG filename expectation and Boolean result apply in the same way.

if not driver.save_screenshot("artifacts/home.png"):
    raise OSError("Screenshot write failed")

Choose whichever name reads more clearly in your codebase. The underlying save behavior is equivalent.

7. A reusable helper for test suites

Centralizing directory creation and return-value handling makes artifact capture consistent. This helper accepts a path, creates its parent directories, and raises an exception if Selenium reports a write failure:

from pathlib import Path
from selenium.webdriver.remote.webdriver import WebDriver

def save_window_screenshot(driver: WebDriver, filename: str | Path) -> Path:
    path = Path(filename).expanduser().resolve()
    path.parent.mkdir(parents=True, exist_ok=True)

    if not driver.get_screenshot_as_file(str(path)):
        raise OSError(f"Selenium could not write screenshot: {path}")

    return path

Call it after the browser reaches the state that should be recorded:

with webdriver.Chrome() as driver:
    driver.get("https://example.com")
    saved_path = save_window_screenshot(driver, "artifacts/example.png")
    print(saved_path)

The helper makes the path absolute before sending it to Selenium and returns the resolved path so logs can identify the artifact. It does not silently retry a write failure: a retry cannot fix a nonexistent or unwritable directory.

8. Or skip the browser setup

If the task is simply to capture a URL to an image or PDF, ScreenshotNeo provides a website screenshot API and MCP server. One GET request returns an image or PDF; the request below follows the supplied API example. See the ScreenshotNeo API documentation for the available parameters.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
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)
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 accepts cookie or consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each of those steps can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server gives AI agents tools for screenshots, page information, and PDF capture. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots.

Sign up for ScreenshotNeo’s free 1,000 screenshots a month, with no card.

9. Troubleshooting

Symptom Likely cause Fix
The method returns False. The operating system rejected the file write. Check that the parent directory exists and is writable. Log the resolved path and run as a user with access to that location.
No file appears, but the script continues. The Boolean result was ignored. Check the return value and raise or report a clear artifact failure.
A warning mentions the filename suffix. The path does not end in .png. Use a .png filename; the method’s documented output is PNG.
Relative output is in an unexpected folder. The process working directory differs from the assumed directory. Resolve an absolute path and log it, or configure the working directory deliberately.
The screenshot shows a loading state or missing content. The capture happened before the desired UI state was ready. Wait for a relevant element or application condition before capturing.
The bottom of a long page is missing. The method captures the current window rather than promising a full-document image. Use a full-page method supported by your browser implementation, or capture the relevant viewport separately.
Captures differ between runs. Viewport size, timing, animations, or dynamic page content differ. Keep viewport and waits consistent; where appropriate, wait for a stable state before saving.

10. Performance, reliability, and storage costs

Screenshot capture requires the browser to render the current window and the client to write the resulting PNG. For a single capture, filesystem setup is usually not the interesting cost; in a large suite, browser startup, navigation, and waiting for application state can dominate elapsed time. Reuse an existing WebDriver session for related captures where your test design permits it, and avoid oversized fixed sleeps.

Saving to disk consumes storage and can slow a run when artifacts are large or written to remote storage. Keep only the screenshots needed for debugging or reporting, and apply retention at the CI artifact layer. If an upload or object store is the destination, the in-memory PNG method can let the application stream bytes onward without first creating a local file.

For reliable artifact handling, make the destination explicit, create parent directories, check the Boolean, and include the output path in logs. A screenshot write failure should be distinguishable from a browser navigation or page-rendering failure; they have different fixes. Also remember that a successful write only confirms that Selenium wrote the image bytes, not that the captured page was semantically correct.

11. Quick checklist

  • Navigate to the intended URL and wait for the UI state you need.
  • Choose a .png filename and make the destination directory first.
  • Use an absolute path when the execution environment’s working directory may vary.
  • Check the Boolean return and surface failed writes.
  • Use a browser-supported full-page API if the whole document is required.
  • Use PNG bytes or Base64 when your workflow needs in-memory data.
  • Keep viewport and capture timing stable when comparing artifacts.

12. FAQ

Does get_screenshot_as_file return the filename?

No. It returns a Boolean indicating whether the write succeeded. Keep the path you passed if your application needs to report or upload it.

Does the method create the parent directory?

No. Create parent directories in your Python code before calling Selenium.

Can I save JPEG by naming the file .jpg?

This method is documented to write PNG. Use a PNG suffix; a different suffix does not change the encoded image format.

Will it capture the whole page?

The documented scope is the current window. Full-page capture depends on a separate API available in the browser implementation you use.

When should I use save_screenshot?

Use it when that name reads better in your code. It delegates to get_screenshot_as_file and shares its behavior.