Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Repair Windows errors before they cause bigger problemsFix Now →When a Selenium element screenshot fails, first determine which operation failed: locating the WebElement, obtaining the PNG, or writing that PNG to disk. A StaleElementReferenceException requires finding the element again; a False return from element.screenshot() points to an output I/O problem. Selenium also has separate element- and window-level screenshot APIs.
Start with the failure you actually have
Selenium’s Python API exposes three relevant element operations: WebElement.screenshot(filename), WebElement.screenshot_as_png, and WebElement.screenshot_as_base64. The first writes a PNG file. The other two return image data for Python to handle. Selenium documents the method as: “Saves a PNG screenshot of the current element to a file.” The same documentation recommends a full path and says the method returns False for an I/O error.
| Symptom | Most likely category | First action |
|---|---|---|
StaleElementReferenceException |
The saved element handle no longer represents a node in the current DOM. | Locate the element again after navigation, refresh, framework updates, or a refreshed frame. |
element.screenshot(path) returns False and no file appears |
Python could not write the destination file. | Use an absolute .png path, create the parent directory, and check write access. |
| You want Python to control saving | The WebDriver command may work while direct file output does not. | Read screenshot_as_png, then call Path.write_bytes(). |
| You receive a whole browser image | You used a driver-level screenshot. | Use WebElement.screenshot() for a crop of one element. |
These behaviors are described in Selenium’s official Python WebElement API documentation.
Use the element API with a real, absolute PNG path
The smallest reliable pattern creates the destination directory, resolves the path, and checks Selenium’s Boolean result:
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
#1 Best Overall
from pathlib import Path
from selenium import webdriver
from selenium.webdriver.common.by import By
output = Path("screenshots/element.png").resolve()
output.parent.mkdir(parents=True, exist_ok=True)
driver = webdriver.Chrome()
try:
driver.get("https://example.com")
element = driver.find_element(By.TAG_NAME, "h1")
saved = element.screenshot(str(output))
if not saved:
raise OSError(f"Could not save screenshot to {output}")
print(f"Saved element screenshot to {output}")
finally:
driver.quit()
Use a filename ending in .png. A relative path can resolve somewhere other than the directory you are inspecting, so an absolute path removes that ambiguity. Creating the parent directory avoids a common write failure, but it cannot override operating-system permissions or a read-only filesystem.
Fix a stale element reference by locating the element again
A WebElement is a reference to a particular DOM node. Selenium considers it stale when that node no longer appears in the current page DOM. Navigation and refreshes can invalidate it; so can a JavaScript framework that replaces the node, or a refreshed frame. The variable still exists in Python, but it no longer identifies an element Selenium can capture.
Do not cache the element across a page change
# Fragile: the page changes before the screenshot
button = driver.find_element(By.CSS_SELECTOR, "#report")
driver.refresh()
button.screenshot("report.png") # may raise StaleElementReferenceException
Find the target after the page is in the state you intend to capture:
Rank #2
from pathlib import Path
from selenium import webdriver
from selenium.common.exceptions import StaleElementReferenceException
from selenium.webdriver.common.by import By
output = Path("screenshots/report.png").resolve()
output.parent.mkdir(parents=True, exist_ok=True)
driver = webdriver.Chrome()
try:
driver.get("https://example.com")
selector = (By.CSS_SELECTOR, "h1")
for attempt in range(2):
try:
element = driver.find_element(*selector)
png_bytes = element.screenshot_as_png
output.write_bytes(png_bytes)
break
except StaleElementReferenceException:
if attempt == 1:
raise
# Re-find the element on the next iteration.
finally:
driver.quit()
The retry is intentionally small: it handles a node replacement while you are locating or capturing, but it does not hide an application that continually rebuilds the DOM. If the page is still changing, capture only after it reaches the state you need, then locate the element at that point.
Separate screenshot capture from file writing
If the direct method returns False, isolate the two operations. screenshot_as_png returns PNG bytes; Python then writes those bytes using its own file API:
from pathlib import Path
output = Path("screenshots/element.png").resolve()
output.parent.mkdir(parents=True, exist_ok=True)
png_bytes = element.screenshot_as_png
if not png_bytes:
raise ValueError("Selenium returned no PNG bytes")
output.write_bytes(png_bytes)
print(f"Wrote {len(png_bytes)} bytes to {output}")
This tells you whether WebDriver returned image data before Python attempted the filesystem write. A PermissionError, missing directory, read-only mount, or invalid destination is then a Python file-output problem rather than an element-screenshot problem. The API also exposes element.screenshot_as_base64 when your next step needs a base64 string instead of raw bytes.
Make sure you are capturing the intended scope
One element
Call element.screenshot(...), element.screenshot_as_png, or element.screenshot_as_base64. These are element-level operations and produce the selected element’s image.
The current browser window
Use the driver-level method when you need the visible current window:
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Scan for outdated or missing drivers - takes under a minute3Clear out junk files and repair common Windows errorsfrom pathlib import Path
output = Path("screenshots/window.png").resolve()
output.parent.mkdir(parents=True, exist_ok=True)
saved = driver.get_screenshot_as_file(str(output))
if not saved:
raise OSError(f"Could not save window screenshot to {output}")
This is not interchangeable with an element capture. A window screenshot includes the current window rather than a tightly cropped WebElement.
Or skip the browser setup
ScreenshotNeo provides a website screenshot API when you do not need to start Selenium and manage a browser driver. One GET request returns a PNG, JPEG, WebP, or PDF. Its element capture option can target one element by CSS selector; it also supports full-page captures, custom waits, JavaScript, headers, cookies, user agents, and other capture controls. See the ScreenshotNeo documentation for the current 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,
)
r.raise_for_status()
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}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const image = Buffer.from(await res.arrayBuffer());
Before capture, ScreenshotNeo accepts the cookie or consent banner like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and response headers identify the page verdict and whether the request was billed. An MCP server supplies take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. The Free plan includes 1,000 screenshots each month without a card; paid plans start at $5 for 3,000 screenshots. Create a free ScreenshotNeo account.
Troubleshoot the common failures
StaleElementReferenceException
- Cause: navigation, refresh, a replaced DOM node, or a refreshed frame invalidated the stored reference.
- Fix: perform the page change first, then call
find_elementagain immediately before the screenshot. If replacement is intermittent, retry once while re-locating.
The method returns False
- Cause: Selenium caught an operating-system I/O error while saving.
- Fix: pass a resolved full path ending in
.png, create the parent directory, confirm the process can write there, and inspect the Boolean instead of ignoring it. If necessary, switch toscreenshot_as_pngand write the bytes yourself.
No file appears, but the script does not show an exception
- Cause: the path may be relative to a different working directory, or the return value was discarded.
- Fix: print
Path(path).resolve(), create the directory, and raise an error whenscreenshot()returnsFalse.
The image is the wrong size or includes more than the target
- Cause: a driver-level screenshot was used instead of the element API.
- Fix: retain the
WebElementreturned byfind_elementand call its screenshot method; reservedriver.get_screenshot_as_filefor the current window.
Bytes work but direct saving does not
- Cause: WebDriver successfully returned PNG data, while the original destination or permissions prevented the write.
- Fix: write
screenshot_as_pngwithPath.write_bytesto a verified writable location, then address the filesystem issue separately.
Reliability and maintenance checks
- Capture after the page has reached the state you want, not before a navigation or DOM replacement.
- Locate the element as close as practical to the capture call; long-lived references are more likely to become stale.
- Use deterministic output names and absolute paths in CI so a working-directory change cannot hide the file.
- Keep the Boolean result from direct file methods and log the resolved path.
- Use bytes when you need to upload, hash, transform, or store the image through another Python API.
- Record the exact Selenium, browser, driver, and operating-system versions when a reproducible failure remains. The cited Selenium 4.49.0 API documentation describes the methods and stale-reference behavior, but it does not settle every browser-driver rendering or platform-permission issue.
FAQ
Does WebElement.screenshot() create JPEG files?
The documented element method saves a PNG and expects a PNG filename. Convert the resulting bytes separately if another image format is required.
Can a stale element be repaired by changing the filename?
No. A filename affects disk output; a stale exception means the stored DOM reference is no longer valid. Re-locate the element after the page or DOM changes.
Best Value
What information should I include when asking for help?
Include the complete exception or Boolean result, the screenshot call, the resolved destination path, and the Selenium, browser, driver, and operating-system versions. That distinguishes a stale-reference problem from an I/O or compatibility problem.
Frequently Asked Questions
Does WebElement.screenshot() create JPEG files?
The documented method saves a PNG. Convert the returned bytes separately if you need another format.
Can changing the filename fix a stale element?
No. A stale reference requires locating the element again after the DOM or page changes.
The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →What should I include in a bug report?
Provide the full exception or Boolean result, screenshot call, resolved path, and Selenium, browser, driver, and operating-system versions.
Quick Recap
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.

