Use Selenium to discover the image URL, then use an HTTP client such as requests to download the original bytes. This two-step approach handles JavaScript-rendered pages without confusing an image file with a screenshot of the browser. Load the page, wait for the intended <img>, read its browser-resolved URL, request that URL, validate the response, and write it in binary mode.
What Selenium does—and what it does not do
Selenium is a browser-automation library. It can open a page, execute its JavaScript, accept a consent dialog, scroll lazy content into view, and locate elements. It is not required to write the original image response to disk. Separating discovery from transfer usually produces simpler and more reliable code.
An image element’s src or currentSrc points to the asset requested by the browser. An HTTP client can then retrieve that URL directly. By contrast, Selenium’s save_screenshot() method saves pixels from the current browser window; it does not return the source file represented by an image element.
Prerequisites and installation
- Python 3.10 or newer, in an isolated virtual environment.
- A supported browser such as Chrome, Edge, or Firefox.
- The Selenium Python package and the
requestsHTTP client.
python -m venv .venv
# macOS/Linux
source .venv/bin/activate
# Windows PowerShell
.venvScriptsActivate.ps1
python -m pip install -U selenium requests
Recent Selenium releases include Selenium Manager, which can locate or manage a compatible browser driver. Browser and driver support changes, so check the Selenium and browser versions used by your project. Always call driver.quit() in cleanup.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
Complete example: find and download a rendered image
The following implementation waits for a specific image, scrolls it into view (useful for lazy loading), chooses currentSrc when available, downloads the response, checks its status and media type, and selects a matching extension. Replace the URL and CSS selector with values from the site you control or are authorized to access.
from pathlib import Path
from urllib.parse import urlparse
import requests
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
PAGE_URL = "https://example.com/gallery"
IMAGE_SELECTOR = "main img.hero" # use a stable selector
OUTPUT_BASENAME = "downloaded-image"
# A conservative mapping; add formats your application accepts.
EXTENSIONS = {
"image/jpeg": ".jpg",
"image/png": ".png",
"image/webp": ".webp",
"image/gif": ".gif",
"image/avif": ".avif",
"image/svg+xml": ".svg",
}
def extension_for(content_type: str, image_url: str) -> str:
media_type = content_type.split(";", 1)[0].strip().lower()
if media_type in EXTENSIONS:
return EXTENSIONS[media_type]
# A URL suffix is only a fallback; query strings are ignored.
suffix = Path(urlparse(image_url).path).suffix.lower()
return suffix if suffix in {".jpg", ".jpeg", ".png", ".webp", ".gif", ".avif", ".svg"} else ".bin"
def main() -> None:
options = webdriver.ChromeOptions()
# options.add_argument("--headless=new") # enable when a visible browser is unnecessary
driver = webdriver.Chrome(options=options)
try:
driver.get(PAGE_URL)
wait = WebDriverWait(driver, 30)
image = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, IMAGE_SELECTOR)))
# Trigger site-specific lazy-loading behavior when needed.
driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", image)
wait.until(lambda d: d.execute_script(
"return arguments[0].complete && arguments[0].naturalWidth > 0;", image
))
image_url = image.get_attribute("currentSrc") or image.get_attribute("src")
if not image_url or image_url.startswith("data:"):
raise RuntimeError("The element has no downloadable HTTP(S) image URL")
response = requests.get(
image_url,
timeout=(10, 60),
headers={"User-Agent": driver.execute_script("return navigator.userAgent;")},
)
response.raise_for_status()
content_type = response.headers.get("Content-Type", "")
if not content_type.lower().split(";", 1)[0].startswith("image/"):
raise RuntimeError(f"Expected an image response, received {content_type or 'no Content-Type'}")
output = Path(OUTPUT_BASENAME + extension_for(content_type, image_url))
output.write_bytes(response.content)
print(f"Saved {len(response.content)} bytes to {output} from {image_url}")
finally:
driver.quit()
if __name__ == "__main__":
main()
presence_of_element_located only proves that the element exists. The additional complete/naturalWidth condition waits for a successfully decoded image. Some applications replace the element or set its URL only after another event; in that case, wait for a page-specific attribute or state instead.
How to get the correct image URL with Selenium
src versus currentSrc
src is the attribute authored in the DOM and may be a placeholder. currentSrc is the URL the browser selected after evaluating srcset and sizes, so it is normally the right choice when you want the variant actually displayed. Use src as a fallback for simple markup.
url = image.get_attribute("currentSrc") or image.get_attribute("src")
print(url)
Lazy-loaded images
Pages commonly store a real URL in attributes such as data-src until the image approaches the viewport. Scroll the element into view, then wait for naturalWidth > 0. If the site uses an intersection observer or a carousel, click or advance that component as a real visitor would before reading the URL.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Clear out junk files and repair common Windows errors3Scan for outdated or missing drivers - takes under a minuteAbsolute and relative URLs
WebDriver generally exposes a resolved URL for the src property. If you read a custom data attribute containing a relative path, resolve it against the page URL with Python’s urllib.parse.urljoin before calling requests.get.
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
Data URLs and blobs
A data: URL embeds the image in the page; it is not an ordinary HTTP resource. A blob: URL belongs to the browser context and usually cannot be fetched by an unrelated HTTP session. For those cases, locate the site’s underlying network/API URL, use the browser’s download control, or extract the rendered pixels deliberately rather than pretending the value is a public file URL.
Keeping browser authentication when downloading
A direct requests call has no Selenium cookies by default. A public image works with the basic example, but a logged-in or signed image may return a login page, a 403 response, or an expired placeholder.
Use Selenium’s browser-synchronized request context
Current Selenium Python APIs document driver.request as an HTTP request context that synchronizes browser cookies. Check the API for the Selenium version you deploy, then use the context for the image request:
with driver.request as client:
response = client.get(image_url, timeout=60)
response.raise_for_status()
content_type = response.headers.get("Content-Type", "")
if not content_type.lower().split(";", 1)[0].startswith("image/"):
raise RuntimeError(f"Unexpected media type: {content_type}")
Path("authenticated-image" + extension_for(content_type, image_url)).write_bytes(response.content)
Because API details can vary by Selenium release, pin and verify the version in your application. If that context is unavailable, copy the cookies deliberately into a requests.Session:
session = requests.Session()
for cookie in driver.get_cookies():
session.cookies.set(cookie["name"], cookie["value"], domain=cookie.get("domain"), path=cookie.get("path", "/"))
response = session.get(image_url, headers={"User-Agent": driver.execute_script("return navigator.userAgent;")}, timeout=60)
response.raise_for_status()
Some sites also require a Referer, authorization header, or a short-lived signed URL. Reproduce only the headers and credentials you are permitted to use, and never log secrets.
Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
Choosing among download approaches
| Approach | Use it when | Trade-off |
|---|---|---|
Selenium discovery plus requests |
The browser reveals a URL that accepts a normal HTTP request | Clean separation and efficient transfer, but cookies and headers must be supplied separately |
| Selenium browser-synchronized request | The image requires the current browser session | Preserves browser cookies through Selenium’s current request API; verify version support |
| Browser-managed download | The site exposes a download or attachment workflow | Download directories, prompts, and completion detection differ by browser; configuration is browser-specific |
| Screenshot | You need the rendered viewport or pixels, not the source asset | Produces a screenshot and loses the original file’s encoding and metadata |
Validate the file before trusting it
- Call
raise_for_status()so a 404, 403, or server error cannot be silently saved as an image. - Inspect
Content-Type; an HTML login page often arrives with a successful HTTP status but is not an image. - Write
response.contentwithPath.write_bytesoropen(..., "wb"). Text mode can corrupt binary data. - Derive the extension from the media type where possible. A query string or a path ending in
.jpgdoes not guarantee JPEG bytes. - For untrusted files, add an image decoder or magic-byte check before further processing, and impose a maximum response size.
Troubleshooting common failures
The selector times out
Check the selector in the browser’s developer tools, account for an iframe, and wait for the page-specific state that creates the image. If the element is inside an iframe, switch first with driver.switch_to.frame(...); switch back with driver.switch_to.default_content() when finished.
The page loaded but the image is absent
Navigation reaching the page-load event does not mean AJAX or other JavaScript work has finished. Replace fixed sleeps with an explicit wait for the target element, a non-placeholder attribute, or a known application condition.
Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchPC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11The URL is empty or points to a tiny preview
Read both currentSrc and src, scroll the element into view, and check whether the page uses a thumbnail link surrounding the image. If you need the original, follow the gallery’s full-size URL rather than downloading the displayed thumbnail.
The response is HTML, 403, or a login page
Confirm the URL in a normal browser tab, then use the synchronized request context or transfer the relevant cookies. A missing Referer, authorization header, expired signed URL, rate limit, or bot challenge can also block a direct request. Do not bypass an access control that you are not authorized to bypass.
The saved file will not open
Print the status and content type, inspect the first bytes, and ensure binary mode was used. A file named .jpg can still contain an HTML error document or WebP data.
Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
Selenium saved a screenshot
driver.save_screenshot("image.png") captures the current browser window. To obtain the original asset, extract the image URL and download its response as shown above. Use a screenshot only when rendered pixels are the intended output.
A download prompt appears
That indicates you chose the browser-managed workflow. Configure the selected browser’s download directory and completion behavior for that browser and version; examples for one browser should not be treated as universal settings.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Performance, reliability, and responsible operation
- Reuse one driver for multiple pages when practical, but quit it when the job ends or fails.
- Use explicit connection and read timeouts. A 10-second connect and 60-second read timeout is a starting point, not a guarantee for every site.
- Prefer the smallest necessary browser window and headless mode for unattended jobs, while debugging visibly first.
- Do not add aggressive retry loops. Respect robots directives, terms, authentication boundaries, and server rate limits; use bounded retries only for transient failures.
- Cache URLs or downloaded bytes when the source permits it, and avoid downloading the same large asset repeatedly.
Or skip the browser setup
When you already know the page URL and need a clean rendered capture rather than the original image bytes, ScreenshotNeo provides a one-call screenshot API. It accepts cookie and consent banners before capture 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 are not billed, and the response identifies the page verdict and billing status in headers. Its MCP server lets Claude, Cursor, or another MCP client call take_screenshot, get_page_info, and capture_pdf.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
See the ScreenshotNeo documentation for all options, including full-page captures, element selectors, device and retina settings, custom CSS or JavaScript, cookies and headers, waits, request blocking, PDF output, caching, signed links, asynchronous jobs, bulk capture, and the usage API.
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}`);
The Free plan includes 1,000 screenshots each month with no card; paid plans start at $5 for 3,000 screenshots. Create a free ScreenshotNeo account.
FAQ
Can I download an image without opening a visible browser?
Yes. Add the appropriate headless option after you have confirmed the selector and waits in a visible session. Headless mode still performs browser rendering; it only changes how the window is displayed.
Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
Should I use the image’s alt text as the filename?
It can be a useful human label, but sanitize it, limit its length, and append the extension determined from the response. Never place unsanitized page text directly into a path.
Why does the browser show an image but my script receives a different variant?
Responsive markup can select a resource based on viewport width, device pixel ratio, and network conditions. currentSrc reports the variant selected in that Selenium session; a separate HTTP request may still need matching cookies or headers.
Frequently Asked Questions
Is Selenium itself an image downloader?
Selenium automates the browser and helps you discover the rendered image URL. A request client or a browser download workflow retrieves the bytes.
Recommended Free Tools
What is the safest wait for a dynamically loaded image?
Wait for the target element and then verify that it is complete with a positive natural width, or wait for a site-specific loaded state.
When should I save a screenshot instead?
Use a screenshot when the required artifact is the rendered page or viewport. Download the source URL when you need the original image file.
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.

