二、scrapy的高性能持久化存储操作

scrapy的高性能持久化存储操作

  • 基于终端指令的持久化存储
    • 保证爬虫文件的parse方法中有可迭代类型对象(通常为列表or字典)的返回,该返回值可以通过终端指令的形式写入指定格式的文件中进行持久化操作。
import scrapy
class QiushiSpider(scrapy.Spider):
    #
    name = 'qiuShi'
    start_urls = ['https://www.qiushibaike.com/text']

    #基于parse返回值进行数据的存储
    def parse(self, response):
    #content_list = [] #用于存储解析到的数据
        dict_lists = []
        div_list = response.xpath('//*[@id="content"]/div/div[2]/div')
        print(type(div_list))
        for div in div_list:
            name = div.xpath('./div[1]/a[2]/h2/text()')[0].extract()
            content = div.xpath('./a//span/text()').extract()
            new = ''.join(content)
    #将解析到的内容封装到字典中
            dict = {
                'name': name,
                'content': content
            }
      #将数据存储到dict_lists这个列表中
            dict_lists.append(dict)
        #     返回列表
        return dict_lists
  • 执行指令:

    • 执行输出指定格式进行存储:将爬取到的数据写入不同格式的文件中进行存储
      scrapy crawl 爬虫名称 -o xxx.json
      scrapy crawl 爬虫名称 -o xxx.xml
      scrapy crawl 爬虫名称 -o xxx.csv
  • 基于管道的持久化存储操作

    • scrapy框架中已经为我们专门集成好了高效、便捷的持久化操作功能,我们直接使用即可。要想使用scrapy的持久化操作功能,我们首先来认识如下两个文件:

    • items.py:数据结构模板文件。定义数据属性。

    • pipelines.py:管道文件。接收数据(items),进行持久化操作。

    • 持久化流程:

      • 1.爬虫文件爬取到数据后,需要将数据封装到items对象中。
      • 2.使用yield关键字将items对象提交给pipelines管道进行持久化操作。
      • 3.在管道文件中的process_item方法中接收爬虫文件提交过来的item对象,然后编写持久化存储的代码将item对象中存储的数据进行持久化存储
      • 4.settings.py配置文件中开启管道
    • 小试牛刀:将糗事百科首页中的段子和作者数据爬取下来,然后进行持久化存储

      import scrapy
      # 导入QiushiItem对象
      from qiushi.items import QiushiItem
      
      class QiushiSpider(scrapy.Spider):
          #
          name = 'qiuShi'
          start_urls = ['https://www.qiushibaike.com/text']
          def parse(self, response):
              dict_lists = []
              div_list = response.xpath('//*[@id="content"]/div/div[2]/div')
              print(type(div_list))
              for div in div_list:
                 # xpath函数返回的为列表,列表中存放的数据为Selector类型的数据。我们解析到的内容被封装							在了Selector对象中,需要调用extract()函数将解析的内容从Selecor中取出。
                  name = div.xpath('./div[1]/a[2]/h2/text()')[0].extract()
                  content = div.xpath('./a//span/text()').extract()
                  new = ''.join(content)
                  #将解析到的数据封装至items对象中
                  qt = QiushiItem()
                  qt['name'] = name
                  qt['content'] = new
                  #提交item到管道文件(pipelines.py)
                  yield qt
      
    • items文件:items.py

      # Define here the models for your scraped items
      #
      # See documentation in:
      # https://docs.scrapy.org/en/latest/topics/items.html
      
      import scrapy
      
      class QiushiItem(scrapy.Item):
          # define the fields for your item here like:
          # 存储作者名称
          name = scrapy.Field()
          # 存储文本内容
          content = scrapy.Field()
      
      
    • 管道文件:pipelines.py

      # Define your item pipelines here
      #
      # Don't forget to add your pipeline to the ITEM_PIPELINES setting
      # See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
      
      
      # useful for handling different item types with a single interface
      from itemadapter import ItemAdapter
      
      
      class QiushiPipeline:
      
          def __init__(self):
              # 构造方法
              self.fp = None  # 定义一个文件描述符属性
      
      
          def open_spider(self, spider):
              print('开始爬虫')
              self.fp = open('./qiushi.txt', 'w', encoding='utf-8')
      
          # 因为该方法会被执行调用多次,所以文件的开启和关闭操作写在了另外两个只会各自执行一次的方法中。
          def process_item(self, item, spider):
              name = item['name']
              content = item['content']
              # #将爬虫程序提交的item进行持久化存储
              self.fp.write(name+':'+content+'\n')
              return item
      
          # 结束爬虫时,执行一次
          def close_spider(self,spider):
              print('爬虫结束')
              self.fp.close()
      
    • 配置文件settings

      #开启管道
      ITEM_PIPELINES = {
          'qiushi.pipelines.QiushiPipeline': 300,
          #     300代表优先级
      
      }
      
posted @ 2021-01-28 11:51  Merry'blog  阅读(58)  评论(0编辑  收藏  举报