Reputation: 104
I am saving image files from the web using Python Requests:
pic_url = bsObj.find('img', {"class":"image lazy-load"})['data-delayed-url']
response = requests.get(pic_url, stream=True)
with open(path + output['name'][0] + '.jpg', 'wb') as out_file:
response.raw.decode_content = True
shutil.copyfileobj(response.raw, out_file)
However, the downloaded files seem all to be corrupted and cannot be opened. What could be the problem here?
EDIT
The code above works! It was a simple spelling mistake (thank you Pedro Lobito)
Upvotes: 1
Views: 2364
Reputation: 98901
Check If pic_url
is correct. Wouldn't it be simpler with urllib
?
import urllib
urllib.urlretrieve(pic_url, path + output['name'][0] + '.jpg')
Upvotes: 2
Reputation: 15806
You need to use the following code:
from io import BytesIO
with open(path + output['name'][0] + '.jpg', 'wb') as out_file:
shutil.copyfileobj(BytesIO(r.content), out_file)
Images are binary data. If you decode them as text, they will get corrupted.
Upvotes: 2