Scrapy进阶知识点总结(四)——Item Pipeline

Item Pipeline

Item Pipeline调用发生在Spider产生Item之后。当Spider解析完Response之后,Item就会传递到Item Pipeline,被定义的Item Pipeline组件会顺次调用,完成一连串的处理过程,比如数据清洗、存储等。

Item Pipeline的主要用途是:

  • 清理HTML数据。
  • 验证爬取数据,检查爬取字段。
  • 查重并丢弃重复内容。
  • 将爬取结果保存到数据库。

Pipeline类

可以自定义管道类,但每个管道类必须实现以下方法:

process_item(self, item, spider)

process_item()是必须要实现的方法,被定义的Item Pipeline会默认调用这个方法对Item进行处理。比如,我们可以进行数据处理或者将数据写入到数据库等操作。它必须返回Item类型的值或者抛出一个DropItem异常。

参数:

  • item,是Item对象,即被处理的Item。
  • spider,是Spider对象,即生成该Item的Spider。

除了process_item()必须实现,管道类还有其它的方法实现:

1.open_spider(spider)

在Spider开启时被调用,主要做一些初始化操作,如连接数据库等。参数是即被开启的Spider对象

2.close_spider(spider)

在Spider关闭时被调用,主要做一些如关闭数据库连接等收尾性质的工作。参数spider就是被关闭的Spider对象

3.from_crawler(cls,crawler)

类方法,用@classmethod标识,是一种依赖注入的方式。它的参数是crawler,通过crawler对象,我们可以拿到Scrapy的所有核心组件,如全局配置的每个信息,然后创建一个Pipeline实例。参数cls就是Class,最后返回一个Class实例。

激活Item Pipeline组件

要激活Item Pipeline组件,必须将其类添加到 ITEM_PIPELINES设置中,如下例所示

ITEM_PIPELINES = {
    ‘myproject.pipelines.Pipelineclass1‘: 300,
    ‘myproject.pipelines.Pipelineclass2‘: 800,
}

设置中为类分配的整数值决定了它们运行的??顺序:项目从较低值到较高值类别。习惯上在0-1000范围内定义这些数字。

示例

1.写入文件

import json

class JsonWriterPipeline(object):

    def open_spider(self, spider):
        self.file = open(‘items.jl‘, ‘w‘)

    def close_spider(self, spider):
        self.file.close()

    def process_item(self, item, spider):
        line = json.dumps(dict(item)) + "\n"
        self.file.write(line)
        return item

2.存入mysql

import pymysql
class MySQLPipeline(object):
    def __init__(self):
        # 连接数据库
        self.db = pymysql.connect(
            host=‘localhost‘,  # 数据库IP地址
            port=3306,  # 数据库端口
            db=‘dbname‘,  # 数据库名
            user=‘root‘,  # 数据库用户名
            passwd=‘root‘,  # 数据库密码
            charset=‘utf8‘,  # 编码方式
            )
        # 使用cursor()方法获取操作游标
        self.cursor = self.db.cursor()

    def process_item(self, item, spider):
        #编写insert sql语句,这里是数据库中已经有表了
        sql =  "INSERT INTO EMPLOYEE(FIRST_NAME,LAST_NAME) VALUES (‘%s‘, ‘%s‘)" %(item[‘F_name‘],item[‘L_name‘])
        try:
            # 执行sql语句
            self.cursor.execute(sql)
            # 提交sql语句
            self.db.commit()
        except:
            # 发生错误时回滚
            self.db.rollback()
        # 返回item
        return item 

    def close_spider(self, spider):
        self.db.close()

3.存入mongodb

import pymongo
class MongodbPipeline(object):

    def __init__(self):
        # 建立MongoDB数据库连接
        self.client = pymongo.MongoClient(‘mongodb://localhost:27017/‘)
        # 连接所需数据库
        self.db = client[‘scrapy‘]
        # 连接集合(表)
        self.coll = db[‘collection_name‘]

    def process_item(self, item, spider):
        postItem = dict(item)  # 把item转化成字典形式
        self.coll.insert(postItem)  # 向数据库插入一条记录
        return item 

    def close_spider(self, spider):
        self.client.close()

4.from_crawler()实例

class MongoPipeline(object):
    collection_name = ‘xxx‘

    def __init__(self, mongo_uri, mongo_db):
        self.mongo_uri = mongo_uri
        self.mongo_db = mongo_db

    @classmethod
    def from_crawler(cls, crawler):
        return cls(
            #从crawler setting中获取配置
            mongo_uri=crawler.settings.get(‘MONGO_URI‘),
            mongo_db=crawler.settings.get(‘MONGO_DATABASE‘)
        )

    def open_spider(self, spider):
        self.client = pymongo.MongoClient(self.mongo_uri)
        self.db = self.client[self.mongo_db]

    def close_spider(self, spider):
        self.client.close()

    def process_item(self, item, spider):
        postItem = dict(item)
        self.db[self.collection_name].insert(postItem)
        return item

原文地址:https://www.cnblogs.com/fengf233/p/11363620.html

时间: 2024-08-28 05:30:23

Scrapy进阶知识点总结(四)——Item Pipeline的相关文章

Scrapy爬虫框架第七讲【ITEM PIPELINE用法】

ITEM PIPELINE用法详解:  ITEM PIPELINE作用: 清理HTML数据 验证爬取的数据(检查item包含某些字段) 去重(并丢弃)[预防数据去重,真正去重是在url,即请求阶段做] 将爬取结果保存到数据库中 ITEM PIPELINE核心方法(4个) (1).open_spider(spider) (2).close_spider(spider) (3).from_crawler(cls,crawler) (4).process_item(item,spider) 下面小伙伴

爬虫框架Scrapy之Item Pipeline

Item Pipeline 当Item在Spider中被收集之后,它将会被传递到Item Pipeline,这些Item Pipeline组件按定义的顺序处理Item. 每个Item Pipeline都是实现了简单方法的Python类,比如决定此Item是丢弃而存储.以下是item pipeline的一些典型应用: 验证爬取的数据(检查item包含某些字段,比如说name字段) 查重(并丢弃) 将爬取结果保存到文件或者数据库中 编写item pipeline 编写item pipeline很简单

【scrapy】Item Pipeline

After an item has been scraped by a spider,it is sent to the Item Pipeline which process it through several components that are executed sequentially. Each item pipeline component is a single python class that must implement the following method: pro

python爬虫之Scrapy框架中的Item Pipeline用法

当Item在Spider中被收集之后, 就会被传递到Item Pipeline中进行处理. 每个item pipeline组件是实现了简单的方法的python类, 负责接收到item并通过它执行一些行为, 同时也决定此item是否继续通过pipeline, 或者被丢弃而不再进行处理. item pipeline的主要作用 : 1. 清理html数据 2. 验证爬取的数据 3. 去重并丢弃 4. 将爬取的结果保存到数据库中或文件中 编写自己的item pipeline : process_item

Python爬虫从入门到放弃(十六)之 Scrapy框架中Item Pipeline用法

原文地址https://www.cnblogs.com/zhaof/p/7196197.html 当Item 在Spider中被收集之后,就会被传递到Item Pipeline中进行处理 每个item pipeline组件是实现了简单的方法的python类,负责接收到item并通过它执行一些行为,同时也决定此Item是否继续通过pipeline,或者被丢弃而不再进行处理 item pipeline的主要作用: 清理html数据 验证爬取的数据 去重并丢弃 讲爬取的结果保存到数据库中或文件中 编写

爬虫(十六):Scrapy框架(三) Spider Middleware、Item Pipeline、对接Selenium

1. Spider Middleware Spider Middleware是介入到Scrapy的Spider处理机制的钩子框架. 当Downloader生成Response之后,Response会被发送给Spider,在发送给Spider之前,Response会首先经过Spider Middleware处理,当Spider处理生成Item和Request之后,Item Request还会经过Spider Middleware的处理. Spider Middleware有三个作用: 我们可以在D

Python进阶(三十四)-Python3多线程解读

Python进阶(三十四)-Python3多线程解读 线程讲解 ??多线程类似于同时执行多个不同程序,多线程运行有如下优点: 使用线程可以把占据长时间的程序中的任务放到后台去处理. 用户界面可以更加吸引人,这样比如用户点击了一个按钮去触发某些事件的处理,可以弹出一个进度条来显示处理的进度. 程序的运行速度可能加快. 在一些等待的任务实现上如用户输入.文件读写和网络收发数据等,线程就比较有用了.在这种情况下我们可以释放一些珍贵的资源如内存占用等等. ??线程在执行过程中与进程还是有区别的.每个独立

4.4. Item Pipeline管道文件

一:Item Pipeline 当Item在Spider中被收集之后,它将会被传递到Item Pipeline,这些Item Pipeline组件按定义的顺序处理Item. 每个Item Pipeline都是实现了简单方法的Python类,比如决定此Item是丢弃而存储.以下是item pipeline的一些典型应用: 验证爬取的数据(检查item包含某些字段,比如说name字段) 查重(并丢弃) 将爬取结果保存到文件或者数据库中 二:编写item pipeline 编写item pipelin

Item Pipeline

当Item在Spider中被收集之后,它将会被传递到Item Pipeline,一些组件会按照一定的顺序执行对Item的处理. 每个item pipeline组件(有时称之为"Item Pipeline")是实现了简单方法的Python类.他们接收到Item并通过它执行一些行为,同时也决定此Item是否继续通过pipeline,或是被丢弃而不再进行处理. 以下是item pipeline的一些典型应用: 清理HTML数据 验证爬取的数据(检查item包含某些字段) 查重(并丢弃) 将爬