zoukankan      html  css  js  c++  java
  • scrapy框架持久化存储

    scrapy框架持久化存储

    1. 基于终端指令的持久化存储

    2. 基于管道的持久化存储

    基于终端指令的持久化存储

    - 保证爬虫文件的parse方法中有可迭代对象(通常为列表or字典)的返回,该返回值可以通过终端指令的形式写入指定格式(.json/.xml/.csv)的文件中进行持久化操作.

    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
    from ..items import QiuBaiProItem
    
    class QiuBaiSpider(scrapy.Spider):
        name = 'QiuBai'
        allowed_domains = ['www.qiushibaike.com']
        start_urls = ['http://www.qiushibaike.com/']
    
        def parse(self, response):
            odiv = response.xpath('//div[@id="content-left"]/div')
            for div in odiv:
                # xpath函数返回的为列表,列表中存放的数据为Selector类型的数据。我们解析到的内容被封装在了Selector对象中,需要调用extract()函数将解析的内容从Selecor中取出。
                author = div.xpath('.//div[@class="author clearfix"]//h2/text()').extract_first()
                author = author.strip('
    ')#过滤空行
                content = div.xpath('.//div[@class="content"]/span/text()').extract_first()
                content = content.strip('
    ')#过滤空行
    
                #将解析到的数据封装至items对象中
                item = QiuBaiProItem()
                item['author'] = author
                item['content'] = content
    
                yield item#提交item到管道文件(pipelines.py)
    QiuBai.py

    items文件

    import scrapy
    
    class SecondbloodItem(scrapy.Item):
        # define the fields for your item here like:
        # name = scrapy.Field()
        author = scrapy.Field() #存储作者
        content = scrapy.Field() #存储段子内容
    items.py

    管道文件:pipelines.py

    class QiuBaiProPipeline(object):
        #构造方法
        def __init__(self):
            self.fp = None  #定义一个文件描述符属性
      #下列都是在重写父类的方法:
        #开始爬虫时,执行一次
        def open_spider(self,spider):
            print('爬虫开始')
            self.fp = open('./data.txt', 'w')
    
       #因为该方法会被执行调用多次,所以文件的开启和关闭操作写在了另外两个只会各自执行一次的方法中。
        def process_item(self, item, spider):
            #将爬虫程序提交的item进行持久化存储
            self.fp.write(item['author'] + ':' + item['content'] + '
    ')
            return item
    
        #结束爬虫时,执行一次
        def close_spider(self,spider):
            self.fp.close()
            print('爬虫结束')
    pipelines.py

    配置文件:settings.py

    #开启管道
    ITEM_PIPELINES = {
        'qiuBaiPro.pipelines.QiuBaiProPipeline': 300, #300表示为优先级,值越小优先级越高
    }
    settings.py

    基于mysql的管道存储

    上述案例中,在管道文件里将item对象中的数据值存储到了磁盘中,如果将item数据写入mysql数据库的话,只需要将上述案例中的管道文件修改成如下形式:

    #导入数据库的类
    import pymysql
    class QiubaiproPipelineByMysql(object):
    
        conn = None  #mysql的连接对象声明
        cursor = None#mysql游标对象声明
        def open_spider(self,spider):
            print('开始爬虫')
            #链接数据库
            self.conn = pymysql.Connect(host='127.0.0.1',port=3306,user='root',password='123456',db='qiubai')
        #编写向数据库中存储数据的相关代码
        def process_item(self, item, spider):
            #1.链接数据库
            #2.执行sql语句
            sql = 'insert into qiubai values("%s","%s")'%(item['author'],item['content'])
            self.cursor = self.conn.cursor()
            #执行事务
            try:
                self.cursor.execute(sql)
                self.conn.commit()
            except Exception as e:
                print(e)
                self.conn.rollback()
    
            return item
        def close_spider(self,spider):
            print('爬虫结束')
            self.cursor.close()
            self.conn.close()

    然后注册到settings.py文件中.

    基于redis的管道存储

    import redis
    
    class QiubaiproPipelineByRedis(object):
        conn = None
        def open_spider(self,spider):
            print('开始爬虫')
            #创建链接对象
            self.conn = redis.Redis(host='127.0.0.1',port=6379)
        def process_item(self, item, spider):
            dict = {
                'author':item['author'],
                'content':item['content']
            }
            #写入redis中
            self.conn.lpush('data', dict)
            return item

    然后注册到settings.py文件中.

    注意:

    如果要将同一份数据存储到不同的文件(磁盘文件,数据库)中怎么办?

    管道文件中定义多个类,每个类负责一种方式的存储,每个类中的process_item方法都要return item,将item传递给下一个即将被执行的管道类.

  • 相关阅读:
    Git ignore file for Xcode projects
    How can I create a zip archive of a whole directory via terminal without hidden files?
    What is a bare git repository?
    How to tell if UIViewController's view is visible
    Adding A Shadow To UIView
    Properties
    iOS中nil,Nil,NULL之间的区别
    FMDB的简单使用
    iOS 加载图片选择imageNamed 方法还是 imageWithContentsOfFile?
    对retain 和 assign的理解
  • 原文地址:https://www.cnblogs.com/yaraning/p/10827764.html
Copyright © 2011-2022 走看看