zoukankan      html  css  js  c++  java
  • scrapy图片数据爬取之ImagesPipeline

    基于scrapy爬取字符串类型的数据和爬取图片类型的数据区别?

    • 字符串:只需要基于xpath进行解析且提交管道进行持久化存储
    • 图片:xpath解析出图片src的属性值,单独的对图片地址发起请求获取图片二进制类型的数据

    ImagesPipeline:

    只需要将img的src的属性值进行解析,提交到管道,管道就会对图片的src进行请求发送获取图片的二进制类型的数据,且还会帮我们进行持久化存储。


    需求:爬取站长素材的高清图片

    使用流程:

    1、数据解析(图片的地址)

    import scrapy
    from imgsPro.items import ImgsproItem
    
    class ImgSpider(scrapy.Spider):
        name = 'img'
        # allowed_domains = ['www.xxx.com']
        start_urls = ['http://sc.chinaz.com/tupian/']
    
        def parse(self, response):
            div_list = response.xpath('//div[@id="container"]/div')
            for div in div_list:
                # src = div.xpath('.//div/a/img/@src').extract_first()
                # 注意:使用伪属性
                src = div.xpath('.//div/a/img/@src2').extract_first()
                item = ImgsproItem()
                item['src'] = src
    
                yield item
    import scrapy
    
    
    class ImgsproItem(scrapy.Item):
        # define the fields for your item here like:
        src = scrapy.Field()

    2、将存储的图片地址的item提交到制定的管道类

    3、在管道文件中自定制一个基于ImagesPipeline的一个管道类,并重写以下方法

    • get_media_requests # 就是可以根据图片地址进行图片数据的请求
    • file_path # 指定图片存储的路径
    • item_completed # 返回给下一个即将被执行的管道类
    from scrapy.pipelines.images import ImagesPipeline
    import scrapy
    
    class imagesPipeLine(ImagesPipeline):
        # 就是可以根据图片地址进行图片数据的请求
        def get_media_requests(self, item, info):
            yield scrapy.Request(item['src'])
    
        # 指定图片存储的路径
        def file_path(self, request, response=None, info=None):
            imgName = request.url.split('/')[-1]
            return imgName
    
        def item_completed(self, results, item, info):
            return item  # 返回给下一个即将被执行的管道类

    4、在配置文件中

    • 指定图片存储的目录:IMAGES_STORE = './imgs_me'
    • 指定开启的管道:自定制的管道类
    # 指定图片存储的目录,没有即自动创建
    IMAGES_STORE = './imgs_me'
    
    
    ITEM_PIPELINES = {
       'imgsPro.pipelines.imagesPipeLine': 300,
    }
  • 相关阅读:
    bzoj1098 1301
    bzoj3237
    bzoj3170
    bzoj4008
    一些题解
    bzoj4028
    bzoj3196
    redis学习
    quartz学习
    电商618 压测、优化、降级预案
  • 原文地址:https://www.cnblogs.com/nanjo4373977/p/12988899.html
Copyright © 2011-2022 走看看