我使用以下方法下载图片:
newlink = image.img['src']
print('Downloading image', index)
try:
response = requests.get(newlink, stream=True)
sleep(1)
with open(image_path, 'wb') as file:
sleep(1)
shutil.copyfileobj(response.raw, file)
except Exception as e:
print(e)
print('Could not download image number ', index)一切都运行得很好,但我注意到,当我每天运行脚本时,几天(5-7)后,下载每个图像需要很多时间。当这种情况发生时,我关闭了pycharm并重启了我的电脑。在那之后,它又开始正常工作了。
我想知道是否有人知道为什么会发生这种情况。
谢谢
发布于 2019-02-02 17:07:44
这可能是内存或网络堆栈问题。根据文档:http://docs.python-requests.org/en/master/user/advanced/
如果在发出请求时将stream设置为True,则除非您使用所有数据或调用Response.close,否则请求无法将连接释放回池。这可能会导致连接效率低下。如果您在使用stream=True时发现自己部分读取请求正文(或者根本不读取它们),则应该在with语句中发出请求,以确保它始终处于关闭状态:
with requests.get('https://httpbin.org/get', stream=True) as r:
# Do things with the response here.试一试:
newlink = image.img['src']
print('Downloading image', index)
try:
with requests.get(newlink, stream=True) as response:
sleep(1)
with open(image_path, 'wb') as file:
sleep(1)
shutil.copyfileobj(response.raw, file)
except Exception as e:
print(e)
print('Could not download image number ', index)https://stackoverflow.com/questions/54477016
复制相似问题