Save Images from Browser with Selenium in Python
In this article
Saving images from a web browser using Selenium in Python involves identifying the image element, extracting its source URL (src attribute), and using a separate library like requests to download the binary data of that image to your local drive. Selenium itself is designed for browser automation and interaction, not for file transfers, which is why combining it with a HTTP library is the most efficient and stable approach.
What You'll Need
- Python installed on your system (3.7 or higher recommended).
- Selenium library (
pip install selenium). - Requests library (
pip install requests) for handling the image download. - A WebDriver corresponding to your browser (e.g., ChromeDriver for Google Chrome or GeckoDriver for Firefox).
- The browser itself installed on your machine.
Step-by-Step
- Set Up Your Environment: Import the necessary modules. You will need
webdriverfrom Selenium to control the browser andrequeststo save the image file. - Initialize the WebDriver: Create an instance of the browser driver. For Chrome, this would be
driver = webdriver.Chrome(). This opens a fresh browser window that your Python script can control. - Navigate to the Target Page: Use
driver.get("URL")to load the website containing the images you wish to save. - Locate the Image Element: Use Selenium's locator strategies to find the image. You can use
find_element(By.ID, "id_name"),By.CSS_SELECTOR, orBy.XPATH. If you want to save multiple images, usefind_elementsto return a list of all matching image tags. - Extract the Image Source URL: Once the element is found, retrieve the
srcattribute. This is the actual web address of the image file. In Python, this is done viaimage_url = element.get_attribute("src"). - Handle Relative URLs: Some websites use relative paths (e.g.,
/images/photo.jpg) instead of absolute URLs. Check if the URL starts with "http". If it does not, prepend the website's base domain to the string to create a valid absolute link. - Download the Image Data: Pass the absolute URL to
requests.get(image_url). This fetches the raw bytes of the image from the server. - Write the File to Disk: Open a local file in "write binary" mode (
wb) and write the content of the request response to that file. Ensure you provide a valid file extension (like .jpg or .png) based on the URL or the content type. - Close the Browser: Always call
driver.quit()at the end of your script to close the browser window and free up system memory.
Common Mistakes
- Trying to "Right-Click Save" via Selenium: Selenium cannot interact with the browser's native context menu (the right-click menu). You must extract the URL and download the file programmatically.
- Ignoring Lazy Loading: Many modern websites only load images as you scroll down. If you try to grab the
srcimmediately, you might get a placeholder image or a null value. You may need to script a scroll action before extracting URLs. - Forgetting Binary Mode: When saving the image file using Python's
open()function, failing to use"wb"(write binary) instead of"w"(write text) will corrupt the image file. - Hardcoding File Names: Using a single filename in a loop will overwrite the previous image. Use a counter or extract a unique ID from the URL to name each file uniquely.
Tips
- Use Headless Mode: If you don't need to see the browser window, run Selenium in headless mode using
Options(). This reduces CPU and RAM usage and speeds up the process. - Set a User-Agent: Some servers block requests that don't look like they come from a real browser. When using the
requestslibrary, pass aheadersdictionary containing a common User-Agent string. - Implement Explicit Waits: Instead of using
time.sleep(), useWebDriverWaitto wait for the image element to be present in the DOM before attempting to extract the URL. - Verify Content Type: Before saving, check the
Content-Typeheader of the response to ensure the URL actually points to an image and not an HTML error page.
Troubleshooting
- Image is a Base64 String: If the
srcattribute starts withdata:image/..., it is not a URL but the image data itself. You will need to strip the header and use thebase64library to decode the string into bytes before saving. - 403 Forbidden Error: This happens when the server detects a bot. Ensure your
requestscall includes the same cookies or headers that the Selenium browser session is using. - ElementNotInteractableException: This occurs if the image is hidden or inside an iframe. If it is in an iframe, use
driver.switch_to.frame()to move the driver's focus into that frame. - Empty Files: If the saved files are 0 KB, it usually means the request failed or the URL was incorrect. Print the URL to the console to verify it opens in a standard browser.
Frequently Asked Questions
Can I save images that require a login?
Yes, but you must use Selenium to perform the login process first. Once logged in, the browser session holds the cookies. You can then extract the cookies from Selenium and pass them into your requests.Session() object to maintain authentication during the download.
How do I save all images on a page at once?
Use driver.find_elements(By.TAG_NAME, "img") to get a list of all image elements. Then, iterate through that list with a for loop, extracting the source and saving each file individually.
Will this work for images generated by JavaScript?
Yes. Because Selenium renders the page like a real browser, it executes JavaScript. As long as the image eventually appears in the DOM as an <img> tag, Selenium can find its source URL.
Is it better to use Selenium or BeautifulSoup for this?
If the page is static HTML, BeautifulSoup is much faster. However, if the images are loaded dynamically via JavaScript or require interaction (like clicking a button to reveal an image), Selenium is necessary.
How do I handle different image formats?
You can determine the format by looking at the end of the URL (e.g., .png, .webp) or by checking the Content-Type header in the HTTP response. Use this information to name your file with the correct extension.