I am trying to download an image from a URL with Python using the requests and shutil libraries. My code is below:
import requests
import shutil
image_url = "https://www.metmuseum.org/-/media/images/visit/met-fifth-avenue/fifthave_teaser.jpg"
with open("image1.jpg", "wb") as file:
response = requests.get(image_url, stream=True)
response.raw.decode_content = True
shutil.copyfileobj(response.raw, file)
file.close()
This code works for most other image urls that I have tried (eg: https://tinyjpg.com/images/social/website.jpg). However, for the image_url in the code, a 1kb file is created with an error that says "It looks like we don't support this file format."
I have also tried:
import urllib
urllib.request.urlretrieve(image_url, "image1.jpg)
It is possible to do this using Seleniumwire - I used driver.requests to get a list of all requests made by the site, and then looped through these requests until I got a request.response.header that included the file type (.jpg). It appears that there are two requests with the same url (the first with content-type 'text/html' and the second with 'image/jpg').
I would like to run this without loading a WebDriver. Is there any way I can download an image like this using the requests function?
file.close()at the end of your code block isn't necessary. Theclose()method is automatically called when leaving thewithblock, whether because the end of the block has been reached, an exception was raised, a control statement likereturnorcontinuewas reached, or any other reason.