Scrapy爬虫爬图

爬取 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



猜你喜欢

转载自www.cnblogs.com/shouwangrenjian/p/10921503.html
今日推荐