首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >下载图片需要很长时间

下载图片需要很长时间
EN

Stack Overflow用户
提问于 2019-02-01 17:57:41
回答 1查看 99关注 0票数 0

我使用以下方法下载图片:

代码语言:javascript
复制
                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并重启了我的电脑。在那之后,它又开始正常工作了。

我想知道是否有人知道为什么会发生这种情况。

谢谢

EN

回答 1

Stack Overflow用户

发布于 2019-02-02 17:07:44

这可能是内存或网络堆栈问题。根据文档:http://docs.python-requests.org/en/master/user/advanced/

如果在发出请求时将stream设置为True,则除非您使用所有数据或调用Response.close,否则请求无法将连接释放回池。这可能会导致连接效率低下。如果您在使用stream=True时发现自己部分读取请求正文(或者根本不读取它们),则应该在with语句中发出请求,以确保它始终处于关闭状态:

代码语言:javascript
复制
with requests.get('https://httpbin.org/get', stream=True) as r:
    # Do things with the response here.

试一试:

代码语言:javascript
复制
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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54477016

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档