python requests download image

Python Requests Download Image

If you are working on a project that requires you to download images using Python, you can do so easily with the help of the Python requests module.

Method 1: Using Requests.get() method

The first method involves using the requests.get() method to download the image from the specified URL. Here is the code:


import requests

url = 'https://example.com/image.jpg'
response = requests.get(url)

open('image.jpg', 'wb').write(response.content)
  • The requests.get() method takes the URL of the image as an argument and returns a response object that contains the image data.
  • The open() function is used to create a new file in binary write mode and write the image data to it.
  • The file is saved with the name image.jpg.

Method 2: Using urllib.request.urlretrieve() method

The second method involves using the urllib.request.urlretrieve() method to download the image. Here is the code:


import urllib.request

url = 'https://example.com/image.jpg'
urllib.request.urlretrieve(url, 'image.jpg')
  • The urllib.request.urlretrieve() method takes the URL of the image and the filename to save it to as arguments.
  • The file is saved with the name image.jpg.

Conclusion

Both methods are effective in downloading an image using Python requests module. However, the first method gives you more control over the response object, while the second method is simpler and easier to use.