下载图片需要很多时间

2024-05-19 11:30:24 发布

您现在位置:Python中文网/ 问答频道 /正文

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

                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并重新启动了我的电脑。之后,它又开始正常工作了。你知道吗

我想知道是否有人知道为什么会这样。你知道吗

谢谢


Tags: 方法图像imagesrcimgindexresponseas
1条回答
网友
1楼 · 发布于 2024-05-19 11:30:24

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

如果在发出请求时将stream设置为True,则请求无法释放回池的连接,除非您使用所有数据或调用响应。关闭. 这会导致连接效率低下。如果在使用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)

相关问题 更多 >

    热门问题