我使用 Python 请求从网络保存图像文件:
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)
但是,下载的文件似乎全部损坏,无法打开。这里可能出现什么问题?
编辑
上面的代码有效!这是一个简单的拼写错误(谢谢佩德罗·洛比托)
最佳答案
您需要使用以下代码:
from io import BytesIO
with open(path + output['name'][0] + '.jpg', 'wb') as out_file:
shutil.copyfileobj(BytesIO(r.content), out_file)
图像是二进制数据。如果您将它们解码为文本,它们将会被损坏。
关于Python 请求 : downloaded image is corrupted,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44225596/