论Scrapy中的数据持久化

引入

Scrapy的数据持久化,主要包括存储到数据库、文件以及内置数据存储。mysql

那咱们今天就来说讲如何把Scrapy中的数据存储到数据库和文件当中。redis

 

终端指令存储

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

# 执行输出指定格式进行存储:将爬取到的数据写入不一样格式的文件中进行存储
    scrapy crawl 爬虫名称 -o xxx.json  # 存为json文件
    scrapy crawl 爬虫名称 -o xxx.xml   # 存为xml文件
    scrapy crawl 爬虫名称 -o xxx.csv   # 存为csv文件

 

管道存储

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

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

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

持久化流程:json

  1. 爬虫文件爬取到数据后,须要将数据封装到items对象中。
  2. 使用yield关键字将items对象提交给pipelines管道进行持久化操做。
  3. 在管道文件中的process_item方法中接收爬虫文件提交过来的item对象,而后编写持久化存储的代码将item对象中存储的数据进行持久化存储数据结构

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

举个栗子

将糗事百科首页中的段子和做者数据爬取下来,而后进行持久化存储app

- qiubaiDemo.py(爬虫文件)框架

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.py(items文件)dom

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(管道文件)scrapy

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表示为优先级,值越小优先级越高
}

 

 基于mysql的管道存储

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

- pipelines.py

# 导入数据库的类
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='123',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,
}

 

基于redis的管道存储

在管道文件里将item对象中的数据值存储到了磁盘中,若是将item数据写入redis数据库的话,只须要将上述案例中的管道文件修改为以下形式:

- pipelines.py

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

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
pipelines.py
# 下列结构为字典,字典中的键值表示的是即将被启用执行的管道文件和其执行的优先级。
ITEM_PIPELINES = {
   'doublekill.pipelines.DoublekillPipeline': 300,
    'doublekill.pipelines.DoublekillPipeline_db': 200,
}

# 上述代码中,字典中的两组键值分别表示会执行管道文件中对应的两个管道类中的process_item方法,实现两种不一样形式的持久化操做。
settings.py
相关文章
相关标签/搜索