Home > Article > Backend Development > How to Download Images from the Web Using Python's urllib?
Downloading a Picture via Urllib and Python
To download images from the web using Python, you can utilize the urllib package. Here's a step-by-step guide using the urllib.urlretrieve function:
Python 2:
import urllib # Example URL and filename url = "http://www.example.com/image.jpg" filename = "image.jpg" urllib.urlretrieve(url, filename)
Python 3:
import urllib.request # Example URL and filename url = "http://www.example.com/image.jpg" filename = "image.jpg" urllib.request.urlretrieve(url, filename)
In the above examples, the urlretrieve function downloads the image from the specified URL and stores it locally in the specified filename.
Additionally, to handle cases where the image may not exist, you can handle any potential IOError exceptions:
try: urllib.request.urlretrieve(url, filename) except IOError as e: print("Error downloading image:", e)
By using this approach, you can retrieve and save images from the web using Python's urllib library.
The above is the detailed content of How to Download Images from the Web Using Python's urllib?. For more information, please follow other related articles on the PHP Chinese website!