scrapy 下载gif图片

本文介绍如何使用scrapy的imagespipeline自定义下载特定格式的GIF图像,通过重写image_downloaded方法来实现直接保存GIF文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

scrapy 的images pipeline 默认将图片转换成通用的格式(JPG)和模式(RGB) 

Come across to this thread. Here's my MyImagesPipeline to download full size gif images by overriding image_downloaded.

class MyImagesPipeline(ImagesPipeline):

    def check_gif(self, image):
        if image.format == 'GIF':
            return True
        # The library reads GIF87a and GIF89a versions of the GIF file format.
        return image.info.get('version') in ['GIF89a', 'GIF87a']

    def persist_gif(self, key, data, info):
        root, ext = os.path.splitext(key)
        key = key + '.gif'
        absolute_path = self.store._get_filesystem_path(key)
        self.store._mkdir(os.path.dirname(absolute_path), info)
        f = open(absolute_path, 'wb')   # use 'b' to write binary data.
        f.write(data)

    def image_downloaded(self, response, request, info):
        checksum = None
        for key, image, buf in self.get_images(response, request, info):
            if checksum is None:
                buf.seek(0)
                checksum = md5sum(buf)
            if key.startswith('full') and self.check_gif(image):
                # Save gif from response directly.
                self.persist_gif(key, response.body, info)
            else:
                self.store.persist_image(key, image, buf, info)
        return checksum
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值