在 python requests 中下载图像的推荐方法

AJW*_*AJW 2 python python-3.x python-requests

我发现有两种使用 python-reuqests 下载图像的方法。

  1. 使用 PIL,如文档中所述(https://requests.readthedocs.io/en/master/user/quickstart/#binary-response-content):

    from PIL import Image
    from io import BytesIO
    i = Image.open(BytesIO(r.content))
    
    Run Code Online (Sandbox Code Playgroud)
  2. 使用流式响应内容:

    r = requests.get(url, stream=True)
    with open(image_name, 'wb') as f:
        for chunk in r.iter_content():
            f.write(chunk)
    
    Run Code Online (Sandbox Code Playgroud)

然而,推荐的下载图像方式是什么?我认为两者都有其优点,我想知道最佳方法是什么。

aah*_*nik 14

我喜欢极简主义的方式。没有什么叫做正确的方法。这取决于您要执行的任务以及您所面临的限制。


import requests

with open('file.png', 'wb') as f:
    f.write(requests.get(url).content)
# if you change png to jpg, there will be no error
Run Code Online (Sandbox Code Playgroud)