使用请求库临时检索图像 [英] temporarily retrieve an image using the requests library

查看:21
本文介绍了使用请求库临时检索图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个网页抓取工具,只需要从网址中抓取图片的缩略图.

I'm writing a web scraper than needs to scrape only the thumbnail of an image from the url.

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

This is my function using, the urlib library.

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')))

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

for various reasons I need to change this to use the requests library, what would be the equivalent for temp saving an image?

推荐答案

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

You could skip saving to a temporary file part and use the corresponding response object directly to create the image:

#!/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.

I've tested it with Pillow 2.9.0 and requests 2.7.0. It should work since Pillow 2.8.

这篇关于使用请求库临时检索图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆