Last modified: Nov 22, 2024 By Alexander Williams
Python Guide: Download Images Using Requests Library
Downloading images using Python's requests library is a common task in web scraping and data collection. This guide will show you how to efficiently download and save images using the requests library.
Before starting, ensure you have the requests library installed. If not, you can install the requests package using pip.
Basic Image Download
Here's a simple example of downloading an image using requests.get()
:
import requests
def download_image(url, file_name):
# Send GET request to the URL
response = requests.get(url)
# Check if request was successful
if response.status_code == 200:
# Open file in binary write mode
with open(file_name, 'wb') as file:
# Write content to file
file.write(response.content)
return True
return False
# Example usage
image_url = "https://example.com/image.jpg"
file_name = "downloaded_image.jpg"
success = download_image(image_url, file_name)
Adding Error Handling
It's important to implement proper error handling when downloading images. Here's an enhanced version with error handling and content type verification:
import requests
from requests.exceptions import RequestException
def download_image_safe(url, file_name):
try:
response = requests.get(url, stream=True)
# Verify content type
if response.headers['content-type'].startswith('image'):
with open(file_name, 'wb') as file:
# Download in chunks for large files
for chunk in response.iter_content(chunk_size=8192):
if chunk:
file.write(chunk)
print(f"Image successfully downloaded: {file_name}")
return True
else:
print("URL does not point to an image")
return False
except RequestException as e:
print(f"Error downloading image: {e}")
return False
# Example usage with error handling
try:
url = "https://example.com/image.jpg"
success = download_image_safe(url, "image.jpg")
except Exception as e:
print(f"Unexpected error: {e}")
Progress Tracking for Large Images
When downloading large images, it's useful to track the progress. Here's how to implement a progress indicator:
import requests
from tqdm import tqdm
def download_with_progress(url, file_name):
response = requests.get(url, stream=True)
total_size = int(response.headers.get('content-length', 0))
with open(file_name, 'wb') as file, tqdm(
desc=file_name,
total=total_size,
unit='iB',
unit_scale=True
) as progress_bar:
for data in response.iter_content(chunk_size=1024):
size = file.write(data)
progress_bar.update(size)
For handling SSL certificate issues when downloading images from secure sites, you might want to check our guide on Python requests SSL verification.
Best Practices
When downloading images with requests, remember these important guidelines:
- Always use
stream=True
for large files - Implement proper error handling
- Verify content types before saving
- Use appropriate file extensions
- Handle timeouts properly
Conclusion
The Python requests library provides a powerful way to download images from the web. By following these examples and best practices, you can create robust image downloading scripts for your projects.
For more advanced usage, including handling redirects and authentication, check out our guide on handling URL redirects with Python requests.