【问题标题】:temporarily retrieve an image using the requests library使用请求库临时检索图像
【发布时间】:2015-12-27 12:35:06
【问题描述】:

我正在编写一个网络抓取工具,而不是只需要从 url 抓取图像的缩略图。

这是我使用的函数,urllib 库。

def create_thumb(self):
    if self.url and not self.thumbnail:
        image = urllib.request.urlretrieve(self.url)

        # Create the thumbnail of dimension size
        size = 350, 350
        t_img = Imagelib.open(image[0])
        t_img.thumbnail(size)

        # Get the directory name where the temp image was stored
        # by urlretrieve
        dir_name = os.path.dirname(image[0])

        # Get the image name from the url
        img_name = os.path.basename(self.url)

        # Save the thumbnail in the same temp directory
        # where urlretrieve got the full-sized image,
        # using the same file extention in os.path.basename()
        file_path = os.path.join(dir_name, "thumb" + img_name)
        t_img.save(file_path)

        # Save the thumbnail in the media directory, prepend thumb
        self.thumbnail.save(
            os.path.basename(self.url),
            File(open(file_path, 'rb')))

由于各种原因,我需要更改它以使用请求库,临时保存图像的等效项是什么?

【问题讨论】:

    标签: python web-scraping python-requests urllib


    【解决方案1】:

    您可以跳过保存到临时文件部分并直接使用相应的响应对象来创建图像:

    #!/usr/bin/env python3
    import urllib.request
    from PIL import Image # $ pip install pillow
    
    im = Image.open(urllib.request.urlopen(url))
    print(im.format, im.mode, im.size)
    

    这是requests模拟:

    #!/usr/bin/env python
    import requests # $ pip install requests
    from PIL import Image # $ pip install pillow
    
    r = requests.get(url, stream=True)
    r.raw.decode_content = True # handle spurious Content-Encoding
    im = Image.open(r.raw)
    print(im.format, im.mode, im.size)
    

    我已经使用Pillow 2.9.0 和requests 2.7.0 对其进行了测试。它应该从Pillow 2.8 开始工作。

    【讨论】:

    • 这也适用于requests~=2.26.0Pillow~=9.0.0
    【解决方案2】:

    您可以写入 io.BytesIO:

    import requests
    
    from PIL import Image
    from io import BytesIO
    
    r = requests.get(self.url)
    b = BytesIO(r.content)
    size = 350, 350
    img = Image.open(b)
    img.thumbnail(size)
    img.save("foo.thumbnail", "JPEG")
    

    【讨论】:

    • 我收到一个错误:文件“/home/david/.virtualenvs/stocksearch/lib/python3.4/posixpath.py”,第 148 行,在 dirname i = p.rfind(sep ) + 1 AttributeError: '_io.BytesIO' 对象没有属性 'rfind'
    • 什么是Imagelib.open
    • 我有一个 Image 类,所以我将 PILLOW Image 类导入为 Imagelib
    • 我添加了一个使用 PIL 保存缩略图的完整工作示例
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-16
    • 2020-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多