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

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

执行输出指定格式进行存储:将爬取到的数据写入不同格式的文件中进行存储

    scrapy crawl 爬虫名称 -o xxx.json

    scrapy crawl 爬虫名称 -o xxx.xml

    scrapy crawl 爬虫名称 -o xxx.csv

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

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

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

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

持久化流程:

    1.爬虫文件爬取到数据后,需要将数据封装到items对象中。

    2.使用yield关键字将items对象提交给pipelines管道进行持久化操作。

    3.在管道文件中的process_item方法中接收爬虫文件提交过来的item对象,然后编写持久化存储的代码将item对象中存储的数据进行持久化存储

    4.settings.py配置文件中开启管道

小试牛刀:将糗事百科首页中的段子和作者数据爬取下来,然后进行持久化存储

- 爬虫文件:qiubaiDemo.py

# -*- coding: utf-8 -*-

import scrapy

from secondblood.items import SecondbloodItem

class QiubaidemoSpider(scrapy.Spider):

    name = 'qiubaiDemo'

    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('\n')#过滤空行

            content = div.xpath('.//div[@class="content"]/span/text()').extract_first()

            content = content.strip('\n')#过滤空行

            #将解析到的数据封装至items对象中

            item = SecondbloodItem()

            item['author'] = author

            item['content'] = content

            yield item#提交item到管道文件(pipelines.py)

- items文件:items.py

import scrapy

class SecondbloodItem(scrapy.Item):

    # define the fields for your item here like:

    # name = scrapy.Field()

    author = scrapy.Field() #存储作者

    content = scrapy.Field() #存储段子内容

- 管道文件:pipelines.py

# -*- coding: utf-8 -*-

# Define your item pipelines here

# Don't forget to add your pipeline to the ITEM_PIPELINES setting

# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html

class SecondbloodPipeline(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'] + '\n')

        return item

    #结束爬虫时,执行一次

    def close_spider(self,spider):

        self.fp.close()

        print('爬虫结束')

- 配置文件:settings.py

#开启管道

ITEM_PIPELINES = {

    'secondblood.pipelines.SecondbloodPipeline': 300, #300表示为优先级,值越小优先级越高

}

2.1 基于mysql的管道存储

小试牛刀案例中,在管道文件里将item对象中的数据值存储到了磁盘中

,如果将item数据写入mysql数据库的话,只需要将上述案例中的管道文件修改成如下形式:

- pipelines.py文件

# -*- coding: utf-8 -*-

# Define your item pipelines here

# Don't forget to add your pipeline to the ITEM_PIPELINES setting

# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html

#导入数据库的类

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

ITEM_PIPELINES = {

    'qiubaiPro.pipelines.QiubaiproPipelineByMysql': 300,

}

2.2 基于redis的管道存储

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

# -*- coding: utf-8 -*-

# Define your item pipelines here

# Don't forget to add your pipeline to the ITEM_PIPELINES setting

# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html

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

自己示例:

import redis

class Qiubaipro1Pipeline(object):
def __init__(self):
self.conn = None
self.key_data = 'dict_data4' def open_spider(self, spider):
print('start ................')
self.conn = redis.Redis(host='127.0.0.1', port=6379, charset='utf-8', db=0, decode_responses=True)
if self.conn.exists(self.key_data):
self.conn.delete(self.key_data) def process_item(self, item, spider):
dict_data = {
'author': item['author'],
'content': item['content'],
}
print(dict_data) self.conn.lpush(self.key_data, str(dict_data)) # python3.6 不能直接存字典进去
return item def close_spider(self, spider):
print('end................')
print(self.conn.lrange(self.key_data, 0, -1))
self.conn.close()

- pipelines.py文件

ITEM_PIPELINES = {

    'qiubaiPro.pipelines.QiubaiproPipelineByRedis': 300,

}

- 面试题:如果最终需要将爬取到的数据值一份存储到磁盘文件,一份存储到数据库中,则应该如何操作scrapy?

- 答:管道文件中的代码为

#该类为管道类,该类中的process_item方法是用来实现持久化存储操作的。

class DoublekillPipeline(object):

    def process_item(self, item, spider):

        #持久化操作代码 (方式1:写入磁盘文件)

        return item

#如果想实现另一种形式的持久化操作,则可以再定制一个管道类:

class DoublekillPipeline_db(object):

    def process_item(self, item, spider):

        #持久化操作代码 (方式1:写入数据库)

        return item

在settings.py开启管道操作代码为:

#下列结构为字典,字典中的键值表示的是即将被启用执行的管道文件和其执行的优先级。

ITEM_PIPELINES = {

   'doublekill.pipelines.DoublekillPipeline': 300,

    'doublekill.pipelines.DoublekillPipeline_db': 200,

}

#上述代码中,字典中的两组键值分别表示会执行管道文件中对应的两个管道类中的process_item方法,实现两种不同形式的持久化操作。

scrapy框架之持久化操作的更多相关文章

  1. (六--二)scrapy框架之持久化操作

    scrapy框架之持久化操作 基于终端指令的持久化存储 基于管道的持久化存储 1 基于终端指令的持久化存储 保证爬虫文件的parse方法中有可迭代类型对象(通常为列表or字典)的返回,该返回值可以通过 ...

  2. 爬虫开发8.scrapy框架之持久化操作

    今日概要 基于终端指令的持久化存储 基于管道的持久化存储 今日详情 1.基于终端指令的持久化存储 保证爬虫文件的parse方法中有可迭代类型对象(通常为列表or字典)的返回,该返回值可以通过终端指令的 ...

  3. scrapy框架之分布式操作

    分布式概念 分布式爬虫: 1.概念:多台机器上可以执行同一个爬虫程序,实现网站数据的分布爬取. 2.原生的scrapy是不可以实现分布式爬虫? a)调度器无法共享 b)管道无法共享 3.scrapy- ...

  4. 6 scrapy框架之分布式操作

    分布式爬虫 一.redis简单回顾 1.启动redis: mac/linux:   redis-server redis.conf windows: redis-server.exe redis-wi ...

  5. scrapy框架的持久化存储

    一 . 基于终端指令的持久化存储 保证爬虫文件的parse方法中有可迭代类型对象(通常为列表or字典)的返回,该返回值可以通过终端指令的形式写入指定格式的文件中进行持久化操作. 执行输出指定格式进行存 ...

  6. 爬虫开发14.scrapy框架之分布式操作

    分布式爬虫 一.redis简单回顾 1.启动redis: mac/linux:   redis-server redis.conf windows: redis-server.exe redis-wi ...

  7. Scrapy 框架,持久化文件相关

    持久化相关 相关文件 items.py 数据结构模板文件.定义数据属性. pipelines.py 管道文件.接收数据(items),进行持久化操作. 持久化流程 1.爬虫文件爬取到数据后,需要将数据 ...

  8. scrapy框架之CrawlSpider操作

    提问:如果想要通过爬虫程序去爬取”糗百“全站数据新闻数据的话,有几种实现方法? 方法一:基于Scrapy框架中的Spider的递归爬取进行实现(Request模块递归回调parse方法). 方法二:基 ...

  9. 爬虫开发11.scrapy框架之CrawlSpider操作

    提问:如果想要通过爬虫程序去爬取”糗百“全站数据新闻数据的话,有几种实现方法? 方法一:基于Scrapy框架中的Spider的递归爬取进行实现(Request模块递归回调parse方法). 方法二:基 ...

随机推荐

  1. ArrayList集合方法

  2. Java Scanner学习记录

    1. Java.util.Scanner可以用来从键盘获取输入 Scanner.next()  只能读取字符,遇到任何的符合都不会输出 Scanner.nextLine()  会完全按照用户输入的st ...

  3. 获取当前 服务 路径 .net

    using System; //例如 AppDomain.CurrentDomain.BaseDirectory + "\\Setting.ini";

  4. CSS vertical-algin的使用

    一.什么vertical-algin vertical的意思就是垂直,algin是对齐的意思,连起来就是“垂直对齐方式”,接下来看看vertical-algin有哪些属性,打开浏览器一看 vertic ...

  5. yum 和 rpm安装mysql彻底删除(转)

    1.yum方式安装的MySQL $ yum remove mysql mysql-server mysql-libs compat-mysql51 $ rm -rf /var/lib/mysq $ r ...

  6. mysql5.5 for linux 安装(转)

    下载地址: http://dev.mysql.com/downloads/mysql/5.5.html#downloads 进入后会有选择系统 选择linux-generic后 又有很多产品选择,我们 ...

  7. 浏览器实现PDF预览

    1.使用jquery.media.js预览PDF <!DOCTYPE html> <html> <head> <meta charset="utf- ...

  8. 认识数据-数据的计量尺度(Levels of Measurement)

    一. 数据的计量尺度(Levels of Measurement) 一般认为,数据是对客观现象计量的结果.按照对事物计量的精确程度,可将所采用的计量尺度由低级到高级分为四个层次: 1.定类尺度(Nom ...

  9. 黄聪:pjax使用心得总结

    初次结识pjax是在使用tower时钟发现的.当时使用时发现网站可以局部刷新,当然我们知道使用ajax也是可以实现局部刷新的. 然而我们知道,使用ajax进行局部刷新时网站的title是不会变化的,并 ...

  10. java设计模式-Observer(2)

    一.模拟AWT事件处理 回顾一下JDK里面按下一个Button,有件事发生,这个东西怎么写: package com.cy.dp.observer.awt; import java.awt.Butto ...