October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
browser automation

How to Download an Image from a Website with Selenium and Python

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.

Use Selenium to load the page and locate the image, then use Python to request the image URL and save the response bytes. This separates browser interaction from file transfer and usually gives you the original image asset rather than a screenshot. For pages that require the browser’s login cookies, Selenium’s Python API also documents a browser-cookie-synchronized request context.

How the download works

Selenium automates a browser: it can open a page, wait for JavaScript-rendered content and find an image element. The browser tells your script which image URL the page is using. An HTTP client then fetches that URL, checks the response and writes the binary bytes to a file.

This is different from calling Selenium’s save_screenshot(). That method saves an image of the current browser window; it does not retrieve the original file referenced by an <img> element. See the Selenium WebDriver API.

The example below is an implementation pattern, not a claim that it has been tested against every site. Replace the example page URL and selector with values for the site you are authorized to access. Selenium’s Python documentation covers supported browser setup, installation and basic navigation; check its current compatibility notes for your Python and browser versions: Selenium Client Driver — Python API documentation.

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

Install Selenium and prepare a browser

Use a virtual environment to keep the project’s dependencies separate. Selenium’s documentation gives pip install -U selenium as the installation command and describes Selenium Manager for driver handling.

  1. Create and activate a virtual environment for your operating system.

  2. Install Selenium and the HTTP client: python -m pip install -U selenium requests.

  3. Install a browser supported by your Selenium setup. Selenium Manager can handle driver management in supported configurations; consult the current Selenium documentation if initialization fails.

    Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  4. Save the script below as download_image.py, then run it with python download_image.py.

Runnable Selenium and Python example

Set PAGE_URL to the page containing the image and IMAGE_SELECTOR to a selector that identifies the intended image. The script waits for the element, scrolls it into view to help trigger lazy loading, checks the rendered URL, downloads the response, checks its status and content type, and saves the bytes with an extension based on that type.

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 = "img.product-image"
OUTPUT_BASE = Path("downloaded-image")

MIME_EXTENSIONS = {
    "image/jpeg": ".jpg",
    "image/png": ".png",
    "image/webp": ".webp",
    "image/gif": ".gif",
    "image/avif": ".avif",
    "image/svg+xml": ".svg",
}


def main():
    driver = webdriver.Chrome()
    try:
        driver.get(PAGE_URL)
        image = WebDriverWait(driver, 20).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, IMAGE_SELECTOR))
        )
        driver.execute_script(
            "arguments[0].scrollIntoView({block: 'center'});", image
        )

        # currentSrc is the URL selected by the browser for responsive images.
        image_url = WebDriverWait(driver, 20).until(
            lambda d: d.execute_script(
                "return arguments[0].currentSrc || arguments[0].src;", image
            ) or False
        )
        if image_url.startswith("data:"):
            raise ValueError("The image is a data URL, not a directly fetchable file URL.")

        response = requests.get(image_url, timeout=30)
        response.raise_for_status()
        content_type = response.headers.get("Content-Type", "").split(";", 1)[0].lower()
        if not content_type.startswith("image/"):
            raise ValueError(
                f"Expected an image response, got Content-Type: {content_type or 'missing'}"
            )

        extension = MIME_EXTENSIONS.get(content_type)
        if extension is None:
            # Use a familiar image extension from the URL only when its type is unknown.
            url_extension = Path(urlparse(image_url).path).suffix.lower()
            extension = url_extension if url_extension in {
                ".jpg", ".jpeg", ".png", ".webp", ".gif", ".avif", ".svg"
            } else ".img"

        output_path = OUTPUT_BASE.with_suffix(extension)
        output_path.write_bytes(response.content)
        print(f"Saved {len(response.content)} bytes to {output_path}")
    finally:
        driver.quit()


if __name__ == "__main__":
    main()

currentSrc is useful when an image uses responsive markup such as srcset: it reflects the source selected by the browser for the current display conditions. The src fallback can help on simpler pages. The selector and timeout are site-dependent, so choose a selector specific enough to avoid saving a logo, thumbnail or unrelated image.

Get the image URL with Selenium

Use a stable CSS selector for the image you actually want. Selenium’s Python API supports ordinary WebDriver navigation and element lookup; its first script guide shows the basic browser workflow.

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

Wait for dynamic and lazy-loaded images

A browser navigation returning does not guarantee that a JavaScript- or AJAX-driven image is ready. Selenium’s navigation guide warns that page-load completion and asynchronous page activity are separate: Selenium navigation documentation.

Prefer an explicit wait for the element or a meaningful page condition over a fixed sleep. If the image is lazy-loaded, scrolling it into view may prompt the page to fetch it. Some sites update the image URL only after scrolling, clicking a gallery thumbnail or accepting a consent prompt; reproduce only the interaction needed for the intended image, then wait for its usable URL.

Presence of the element does not necessarily mean its image pixels have finished loading. If the URL is correct but the server has not yet populated the image, wait for a site-specific condition, or check the element’s complete and naturalWidth properties before continuing. These checks describe browser image state; they do not guarantee that a later standalone HTTP request will be authorized.

Choose how to fetch the bytes

Approach Use it when Trade-off
Selenium discovery plus requests.get() The page reveals a URL that can be fetched directly. Keeps browser automation and file transfer separate, but the standalone request does not automatically share browser cookies.
Selenium browser-synchronized request The image request depends on cookies from the browser session. The Selenium Python API documents driver.request as an HTTP request context with browser cookie synchronization. Check the API for the Selenium version in use before relying on it.
Browser-managed download The site exposes a download link or attachment and the browser download flow is specifically required. Browser download preferences and completion handling vary. A Selenium FAQ includes a Firefox preference example, but it is legacy and browser-specific, not a current universal prescription.
Screenshot You need a picture of the rendered browser view rather than the original image file. Captures rendered pixels, not the source image asset.

Use browser cookies when a direct request is rejected

A successful browser view does not mean a separate HTTP client has the same session. If the image is protected by login or session cookies, a direct requests.get() may return an authorization error, a redirect or an HTML login page.

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

The current Selenium WebDriver API documents driver.request as a request context with browser cookie synchronization. Its exact interface can depend on the installed Selenium version, so consult the Python API reference for the version in your environment. If using a conventional HTTP client instead, you can deliberately transfer the relevant cookies from the browser to that client, but be careful with session credentials and domain/path scope. Do not log or publish authentication cookies.

Validate and save the response safely

Always check the HTTP result before writing a file. raise_for_status() raises an error for unsuccessful HTTP status codes; checking Content-Type helps catch HTML error pages that might otherwise be saved with an image extension. Write response.content in binary mode, as Path.write_bytes() does.

Do not infer the format solely from the URL path. Image URLs may contain query parameters, use extensionless routes or serve a format different from the apparent suffix. Prefer the response MIME type when it is available and valid. The example maps common image MIME types and falls back to a recognized URL extension, then to .img rather than falsely naming an unknown file as JPEG.

Selenium’s older FAQ discusses detecting download content type; its Firefox download-directory preferences are a historical, browser-specific example rather than current cross-browser guidance: Selenium Python Bindings FAQ.

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

Troubleshooting

The image URL is empty, a placeholder or a thumbnail

  • Wait for the page’s real image element and inspect both currentSrc and src.

  • Scroll the element into view if the page uses lazy loading, and wait again for the URL to change.

  • Check for a higher-resolution responsive candidate or a gallery interaction if the displayed image is only a thumbnail. The correct choice depends on the site and your goal.

The page loads but the target image is missing

Navigation completion is not the same as AJAX completion. Verify the selector in the rendered page, wait for a page-specific condition, and test the selector in the browser version you are automating. Drivers and site behavior can differ.

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

The saved file contains HTML or cannot be opened

  • Print the status code and response content type before saving. A login page, access-denied response or redirect may be HTML rather than an image.

  • If the standalone request lacks the browser session, use the browser-cookie-synchronized request context documented for your Selenium version.

  • Write raw response bytes and choose the extension from the actual MIME type where possible.

The browser shows the image but the request fails

The browser may have cookies or headers that the independent HTTP client does not. Check whether the image URL is session-bound and whether the site requires a preceding browser interaction. Use authorized access only; do not attempt to evade access controls.

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

A download prompt appears

This usually means you are following a browser-managed download workflow, not fetching an image URL with an HTTP client. Configure download behavior only for the chosen browser and Selenium version, and handle completion explicitly. The legacy Firefox example is not a general setting for current browsers.

Selenium saves a screenshot rather than the original image

driver.save_screenshot("page.png") captures the current browser window. To download the original image, extract its URL and retrieve its response bytes; use a screenshot only when rendered pixels are what you need.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Performance, reliability and cost

Browser startup and page rendering are generally more work than requesting a known image URL, so reuse a browser session if a job needs to inspect multiple pages. Fetching the bytes through an HTTP client avoids routing the download through browser UI, but adds a second request context whose cookies, headers, redirects and authorization may differ. Apply finite timeouts to both browser waits and HTTP requests, and close the browser in a finally block so failures do not leave it running.

Keep concurrency modest until you understand the target site’s policies and your own browser resources. Respect the site’s terms, access controls, copyright and applicable law; a publicly rendered image is not automatically free to reuse. Avoid repeated retries without limits, which can waste resources or place unnecessary load on a site.

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.

Or skip the browser setup

If your goal is a clean image of the rendered page rather than the original image file, ScreenshotNeo can return a screenshot or PDF from one GET request. It accepts consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups and chat widgets before capture; each step can be turned off. Bot checks, blank pages and failed loads are not billed, and responses identify page verdict and billing status. Its MCP server lets AI agents use screenshot tools, and the free plan includes 1,000 screenshots a month without a card; paid plans start at $5 for 3,000.

Example using cURL (see the ScreenshotNeo documentation):

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com -o shot.webp

For a Python or Node.js integration, see the request examples in the ScreenshotNeo documentation. This captures the page view; it is not a way to retrieve an image element’s original file. Learn about ScreenshotNeo, or sign up free for 1,000 screenshots a month with no card.

Frequently Asked Questions

Can Selenium download an image without Requests?

Yes. You can use Selenium’s browser-synchronized request context for an HTTP request, or configure a browser-managed download. The standalone Requests approach is often simpler when the image URL is directly accessible.

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

Can I download the full-resolution image rather than the displayed variant?

Sometimes. Inspect the page’s responsive-image markup or gallery behavior; the browser-selected currentSrc may be a smaller variant, and sites differ in how they expose larger files.

Does this method work for images generated from a data URL?

Not as a normal HTTP download: a data URL embeds content rather than pointing to a remote image file, so it needs separate decoding logic.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

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

Read next

Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.