Scrapy爬虫爬图

博客提到Scrapy的ImagesPipeline默认会将下载图片转换为JPG格式和RGB模式,导致gif文件下载后成静态图片。可重写ImagesPipeline中的下载方法,也能在PictureSpiderPipeline中处理下载,还给出了详细代码链接。

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

爬取 https://www.zhainanfu.com/tuku 下的图片,分别保存在各自的文件夹。
使用scrapy的ImagesPipeline类,参考https://scrapy-chs.readthedocs.io/zh_CN/latest/topics/images.html,但是官方文档中使用的时默认路径,无法分类保存,需要重写file_path函数,代码如下:
class MyImagesPipeline(ImagesPipeline):
    def get_media_requests(self, item, info):
        yield scrapy.Request(url=item['src'], meta={'item': item})

    def item_completed(self, results, item, info):
        return item

    def file_path(self, request, response=None, info=None):
        item = request.meta["item"]
        img_name =os.path.basename(item['src'])
        image_path = os.path.join(IMAGES_STORE, item['title'], img_name)
        if os.path.exists(image_path):
            md5 = hashlib.md5()
            md5.update(item['src'].encode("utf-8"))
            img_name = md5.hexdigest() + os.path.splitext(img_name)[-1]
            image_path = os.path.join(IMAGES_STORE, item['title'], img_name)
        print(image_path)
        return image_path

另外就是,scrapy的ImagesPipeline默认将所有下载的图片转换成通用的格式(JPG)和模式(RGB),因此对于gif文件下载后就全是静态图片,需要去重写ImagesPipeline中的下载方法,暂时没有做,也可以直接在PictureSpiderPipeline中进行下载处理。

详细代码见:https://github.com/50th/picture_spider/tree/master



转载于:https://www.cnblogs.com/shouwangrenjian/p/10921503.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值