1. 程式人生 > >(六--二)scrapy框架之持久化操作

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

pass 集成 ref 步驟 com fin content none 提交

scrapy框架之持久化操作

  • 基於終端指令的持久化存儲
  • 基於管道的持久化存儲

1 基於終端指令的持久化存儲

  • 保證爬蟲文件的parse方法中有可叠代類型對象(通常為列表or字典)的返回,該返回值可以通過終端指令的形式寫入指定格式的文件中進行持久化操作。
執行輸出指定格式進行存儲:將爬取到的數據寫入不同格式的文件中進行存儲
    scrapy crawl 爬蟲名稱 -o xxx.json
    scrapy crawl 爬蟲名稱 -o xxx.xml
    scrapy crawl 爬蟲名稱 -o xxx.csv

以爬取糗事百科(https://www.qiushibaike.com/text/)為例

import scrapy


class QiubaiSpider(scrapy.Spider):
    name = qiubai# 表示該爬蟲文件的名稱
    allowed_domains = [www.qiushibaike.com/text/]
    start_urls = [https://www.qiushibaike.com/text/]
  
  # 解析函數
def parse(self, response): # response就是對起始url發起請求後,對應的響應對象
author_list
= response.xpath(//div[@id="content-left"]/div) all_data = [] for div in author_list:
       # extract_first()可以將xpath返回列表中第一個列表元素進行extract解析操作 author
= div.xpath(./div/a[2]/h2/text()).extract_first()
       # extract()可以將Selector對象中存儲的數據進行解析操作

        author = div.xpath(‘./div/a[2]/h2/text()‘).extract() content
= div.xpath(./a/div/span/text()).extract_first() dict={ author:author, content:content } all_data.append(dict) return all_data # 可叠代的對象

在終端寫入

執行輸出指定格式進行存儲:將爬取到的數據寫入不同格式的文件中進行存儲
    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配置文件中開啟管道

1 爬蟲文件qiubai.py

# -*- coding: utf-8 -*-
import scrapy
from ..items import FirstProjectItem
‘‘‘基於管道存儲‘‘‘


‘‘‘
1 爬蟲文件中解析數據
2 【items.py】將解析到的數據值全部分裝在item對象中
3 pipelines.py
4 settings.py配置文件

‘‘‘
class QiubaiSpider(scrapy.Spider):
    name = qiubai
    allowed_domains = [www.qiushibaike.com/text/]
    start_urls = [https://www.qiushibaike.com/text/]

    def parse(self, response):

        author_list = response.xpath(//div[@id="content-left"]/div)
   
     for div in author_list:

            author = div.xpath(./div/a[2]/h2/text()).extract_first()
            # author = div.xpath(./div/a[2]/h2/text())[0].extract()
            content = div.xpath(./a/div/span/text()).extract_first()
        ----------------------------------------------------
            items = FirstProjectItem()

            items["author"] = author         重點
            items["content"] = content
            # 提交給管道
            yield items
        ----------------------------------------------------

2 items.py

import scrapy

# items會實例化一個items對象; 用來存儲解析到的數據值


class FirstProjectItem(scrapy.Item):
    # define the fields for your item here like:
   ----------------------------------------- author
= scrapy.Field() content = scrapy.Field() 重點 你在第一步中有幾個要持久化的這就寫上對應的
-----------------------------------------

3 pipelines.py

# 爬蟲文件每向管道提交一次item則process_item方法就會被執行一次
class
FirstProjectPipeline(object):
                # item就是爬蟲文件提交過來的 def process_item(self, item, spider):
return item

4 settings.py

# 第67行
ITEM_PIPELINES = { first_project.pipelines.FirstProjectPipeline: 300, }

依據上面四步我們就學會了基本的“基於管道的持久化”的步驟,但是我們要在piplines.py做一些操作

只是修改第3步pipelines.py

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

# Define your item pipelines here
#
# Dont forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html


class FirstProjectPipeline(object):
# 每次都會打開多次文件,我們重寫 open_spider方法來開文件一次
    fp = None
    def open_spider(self, spider):
        print(開始爬蟲)
        self.fp = open(qiubai1.txt, w, encoding=utf-8)

    def process_item(self, item, spider):

        self.fp.write(item[author]+:+item["content"]+"\n")    # 生成qiubai1.txt文件
        return item

    def close_spider(self,spider):
        print(結束爬蟲)
        self.fp.close()

3 寫入數據庫

import pymysql
class
MysqlPipline(object): cursor = None conn = None def open_spider(self, spider): print(mysql開始) self.conn = pymysql.connect(host=‘127.0.0.1‘, user=‘root‘, password=‘123456‘, port=3306, db=‘s18‘,charset=‘utf8‘) def process_item(self, item, spider): sql = "insert into t_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: self.conn.rollback() return item def close_spider(self, spider): print(mysql結束) self.cursor.close() self.conn.close()

settings.py

ITEM_PIPELINES = {
   first_project.pipelines.FirstProjectPipeline: 300,
   first_project.pipelines.MysqlPipline: 400,           # settings 配置      值越小 越優先
}

4 寫入redis數據庫

wins安裝redis

import redis


class RedisPipline(object):
    
    r = None
    
    def open_spider(self, spider):
        print(redis開始)
        self.r = redis.Redis(host=127.0.0.1, port=6379)

    def process_item(self, item, spider):
        dict = {
            author:item[author],
            content:item[content]
        }
        self.r.lpush(data, dict)
        return item

    def close_spider(self, spider):
        print(redis結束)

settings.py設置

ITEM_PIPELINES = {
   first_project.pipelines.FirstProjectPipeline: 300,
   first_project.pipelines.RedisPipline: 500,
}

我們可以去redis裏面查看

key *   # 查看所有的key
lrange key 0 -1  # 從頭到尾查看key

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