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

Use driver.save_screenshot("path/to/file.png") to capture the current Selenium viewport. Selenium writes a PNG and returns True or False, so production code should check that result. For an individual DOM element, call element.screenshot(...). For screenshots that must stay in memory, use Selenium’s PNG-bytes or base64 methods. Full-document capture is available through Firefox’s WebDriver API.

Choose the screenshot scope and output

The right Selenium method depends on what you need to document:

Need Method Result
Visible browser viewport driver.save_screenshot(path) or driver.get_screenshot_as_file(path) PNG file; Boolean success value
Current viewport without writing a file driver.get_screenshot_as_png() PNG bytes
Current viewport for HTML or text transport driver.get_screenshot_as_base64() Base64 text
One DOM element element.screenshot(path) PNG file; Boolean success value
One element in memory element.screenshot_as_png or element.screenshot_as_base64 Bytes or base64 text
Entire document Firefox get_full_page_screenshot_as_file or save_full_page_screenshot Full-page PNG file

A normal window screenshot is only the viewport currently visible in the browser. It does not automatically include content below the fold.

Set up a dependable Python capture

Install Selenium in the environment that will run the test:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
python -m pip install selenium

The following script creates its output directory, opens a page, captures a viewport PNG, checks the Boolean result, and always closes the browser:

from pathlib import Path
from selenium import webdriver

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

driver = webdriver.Chrome()
try:
    driver.get("https://example.com")
    # Wait for the application-specific ready state here.
    ok = driver.save_screenshot(str(out / "home.png"))
    if not ok:
        raise OSError("Selenium could not write the screenshot")
finally:
    driver.quit()

save_screenshot is the convenient name for Selenium’s PNG-saving operation; get_screenshot_as_file performs the same kind of file capture. Use a full path ending in .png. Selenium can return False when the file cannot be written, so a test that ignores the return value can appear to pass while producing no artifact.

Make pixel dimensions repeatable

Set the browser window before navigating or capturing when image dimensions matter:

driver = webdriver.Chrome()
try:
    driver.set_window_size(1280, 900)
    driver.get("https://example.com")
    if not driver.save_screenshot("screenshots/1280x900.png"):
        raise OSError("Screenshot write failed")
finally:
    driver.quit()

set_window_size takes width and height in pixels. A fixed size makes visual-regression artifacts easier to compare, although browser chrome and driver behavior can still affect the exact image area.

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

Wait for the state you actually want to capture

Selenium captures whatever is rendered when the method runs. A successful file write does not prove that an application finished loading. Decide what “ready” means for your page and wait for that condition before taking the shot.

  • For a static page, navigation followed by a short, deterministic check may be enough.
  • For a single-page application, wait for a stable application-specific element, such as the dashboard container.
  • For data loaded asynchronously, wait until the loading indicator disappears and the result element is present.
  • For animations, disable or wait through the animation if a stable visual comparison is required.

Use explicit waits rather than an arbitrary long sleep when the page exposes a reliable condition:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait

wait = WebDriverWait(driver, 20)
wait.until(lambda d: d.find_element(By.CSS_SELECTOR, "main.dashboard").is_displayed())
if not driver.save_screenshot("screenshots/dashboard.png"):
    raise OSError("Screenshot write failed")

The selector and condition are application-specific; Selenium’s screenshot API does not define a universal readiness rule.

Capture one Selenium element

Use the element API when the artifact should contain a component rather than the whole viewport:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
from selenium.webdriver.common.by import By

element = driver.find_element(By.CSS_SELECTOR, "main")
element_ok = element.screenshot("screenshots/main.png")
if not element_ok:
    raise OSError("Element screenshot write failed")

The element must be located before capture. If the element is outside the visible area, obscured, still changing size, or not present, the screenshot may not represent the state you expect; wait for the element and its content first. Element screenshots are useful for cards, navigation panels, charts, error messages, and other components that would be difficult to crop reliably from a viewport image.

Keep an element screenshot in memory

png_bytes = element.screenshot_as_png
base64_text = element.screenshot_as_base64

Use png_bytes for a binary upload or image-processing pipeline. Use the base64 form when the receiving format is text, such as an HTML image or JSON-like payload.

Get PNG bytes or base64 from the driver

File output is not required. These calls capture the current viewport and return the image directly:

png_bytes = driver.get_screenshot_as_png()
html_image = driver.get_screenshot_as_base64()

For example, write the bytes yourself when your storage layer controls filenames:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
png_bytes = driver.get_screenshot_as_png()
with open("screenshots/raw.png", "wb") as image_file:
    image_file.write(png_bytes)

Base64 is useful for embedding in HTML. A data URL can be assembled by the consumer as data:image/png;base64, followed by the returned text.

Capture a full document with Firefox

A regular screenshot covers the current viewport. Firefox’s Python WebDriver API exposes full-document methods that capture the page beyond the fold:

from selenium import webdriver

 driver = webdriver.Firefox()
try:
    driver.get("https://example.com/long-page")
    ok = driver.get_full_page_screenshot_as_file("screenshots/full-page.png")
    if not ok:
        raise OSError("Full-page screenshot write failed")
finally:
    driver.quit()

Firefox also provides save_full_page_screenshot and PNG/base64 variants in its WebDriver API. These methods are Firefox-specific in the cited Python API. Do not assume the same full-page method name exists on every browser driver; choose the driver and method deliberately in a cross-browser test suite.

Build a reusable capture helper

A small helper centralizes directory creation, naming, and failure handling:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
from pathlib import Path
from selenium import webdriver


def capture_viewport(url: str, filename: str, width: int = 1280, height: int = 900) -> Path:
    output = Path("screenshots") / filename
    output.parent.mkdir(parents=True, exist_ok=True)
    driver = webdriver.Chrome()
    try:
        driver.set_window_size(width, height)
        driver.get(url)
        if not driver.save_screenshot(str(output)):
            raise OSError(f"Selenium could not write {output}")
    finally:
        driver.quit()
    return output

capture_viewport("https://example.com", "example.png")

Keep the URL, viewport size, browser choice, and readiness condition explicit in test code. That makes a changed screenshot explainable instead of silently mixing browser defaults with application changes.

Troubleshoot common failures

The method returns False or no file appears

Check that the destination directory already exists, the process can write there, and the filename ends in .png. Use an absolute or otherwise unambiguous full path while diagnosing permissions. Selenium reports file-writing problems through the Boolean result, so raise an error immediately.

The image is blank or shows a loading screen

The browser captured too early, or navigation reached a page that failed to render. Add an explicit wait for the application’s ready element and inspect the page for an error state before capture. A successful screenshot call only means an image was produced, not that the page content was correct.

The screenshot is cut off

You captured a viewport, not the full document. Set a deliberate window size for a viewport artifact, or use Firefox’s full-document API when a single long PNG is required.

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

The element screenshot is wrong or fails

Verify the CSS selector, wait until the element is displayed, and capture after its contents have settled. If the component changes size during an animation or asynchronous render, wait for the stable condition rather than adding an unrelated delay.

Full-page code works in one browser but not another

Full-document methods in this Python API are exposed by Firefox. Treat them as browser-specific and keep a separate code path when your suite also runs another driver.

Artifacts contain secrets

Screenshots can expose credentials, personal data, tokens, or test accounts that happen to be visible in the browser. Apply your project’s existing redaction and retention rules before uploading artifacts or publishing them.

Performance, reliability, and cost considerations

  • Reuse a browser session for a batch of related captures when isolation requirements permit; starting a new driver for every image adds startup overhead.
  • Use deterministic viewport dimensions and readiness checks to reduce visual noise in CI.
  • Prefer in-memory PNG bytes when a pipeline immediately uploads or processes the image; avoid unnecessary temporary files.
  • Use element captures when reviewers need a focused component, but use full-document capture when context and page flow are important.
  • Keep screenshot filenames tied to the test, URL, viewport, and state so failed artifacts can be traced.
  • Do not treat a screenshot as proof of successful application behavior. Pair the image with assertions for URL, visible content, and the conditions your test requires.
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 you need a clean website image rather than a browser test, ScreenshotNeo provides a single HTTP request that returns PNG, JPEG, WebP, or PDF. It accepts cookie and consent banners before capture 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 the response identifies the result with X-Page-Verdict and X-Billed headers.

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

See the ScreenshotNeo API documentation for all options. A cURL request:

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 call from 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 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 full-page capture with lazy images loaded, CSS-selector element capture, dark mode, 12 device presets plus custom viewports, retina scale, PDF controls, custom CSS and JavaScript, pre-capture clicks, selector hiding, selector/delay/network-idle waits, request and resource blocking, custom headers/cookies/user agents and Authorization, timezone and geolocation, transparent backgrounds, resizing, configurable-TTL caching, signed image links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, a usage API, an OpenAPI specification, and compatibility with parameter names used by other screenshot APIs. An MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.

The Free plan includes 1,000 shots per month without a card. Paid plans start at $5 for 3,000 shots; every feature is available on every plan. Create a free ScreenshotNeo account.

Frequently Asked Questions

Can Selenium save a screenshot as JPEG or WebP?

The documented Selenium methods in this guide save or return PNG data. Convert the PNG afterward if your downstream system requires another format.

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

Does a successful screenshot call prove that the page loaded correctly?

No. It confirms that Selenium produced image data or wrote a file. Add page-specific assertions and readiness checks to verify the captured state.

Should I use a viewport, element, or full-page screenshot for visual tests?

Use a viewport for a fixed above-the-fold contract, an element for a focused component, and Firefox full-document capture when the complete scrollable page is the artifact under review.

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.