一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

scrapy框架ItemPipeline代码使用方法

时间:2022-08-15 编辑:袖梨 来源:一聚教程网

本篇文章小编给大家分享一下scrapy框架ItemPipeline代码使用方法,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

Item Pipeline简介

Item管道的主要责任是负责处理有蜘蛛从网页中抽取的Item,他的主要任务是清晰、验证和存储数据。

当页面被蜘蛛解析后,将被发送到Item管道,并经过几个特定的次序处理数据。

每个Item管道的组件都是有一个简单的方法组成的Python类。

他们获取了Item并执行他们的方法,同时他们还需要确定的是是否需要在Item管道中继续执行下一步或是直接丢弃掉不处理。

调用时间: 当Item在Spider中被收集之后,它将会被传递到Item Pipeline,一些组件会按照一定的顺序执行对Item的处理。

功能:

清理HTML数据

验证爬取的数据(检查item包含某些字段)

查重(并丢弃)

将爬取结果保存到数据库中

一、一个自己的Pipeline类

必须实现以下方法:

process_item(self, item**,** spider**)**

每个item pipeline组件都需要调用该方法,这个方法必须返回一个具有数据的dict,或是 Item(或任何继承类)对象, 或是抛出 DropItem 异常,被丢弃的item将不会被之后的pipeline组件所处理。

参数:

item (Item 对象或者一个dict) – 被爬取的item

spider (Spider 对象) – 爬取该item的spider

open_spider(self, spider)

当spider被开启时,这个方法被调用。参数:spider (Spider对象) – 被开启的spider

from_crawler(cls,crawler)

如果存在,则调用该类方法以从中创建管道实例Crawler。它必须返回管道的新实例。搜寻器对象提供对所有Scrapy核心组件(如设置和信号)的访问;这是管道访问它们并将其功能挂钩到Scrapy中的一种方法。

close_spider(self, spider)

当spider被关闭时,这个方法被调用参数:spider (Spider对象) – 被关闭的spider

二、启用一个Item Pipeline组件

为了启用一个Item Pipeline组件,你必须将它的类添加到 ITEM_PIPELINES 配置,就像下面这个例子:

ITEM_PIPELINES = {
    'myproject.pipelines.PricePipeline': 300,
    'myproject.pipelines.JsonWriterPipeline': 800,
}

分配给每个类的整型值,确定了他们运行的顺序,item按数字从低到高的顺序,通过pipeline,通常将这些数字定义在0-1000范围内。

将item写入JSON文件

以下pipeline将所有爬取到的item,存储到一个独立地items.json 文件,每行包含一个序列化为'JSON'格式的'item':

import json
class JsonWriterPipeline(object):
    def __init__(self):
        self.file = open('items.json', 'wb')
    def process_item(self, item, spider):
        line = json.dumps(dict(item),ensure_ascii=False) + "n"
        self.file.write(line)
        return item

在这里优化:

以下pipeline将所有爬取到的item,存储到一个独立地items.json 文件,每行包含一个序列化为'JSON'格式的'item':

import json
import codecs
class JsonWriterPipeline(object):
    def __init__(self):
        self.file = codecs.open('items.json', 'w', encoding='utf-8')
    def process_item(self, item, spider):
        line = json.dumps(dict(item), ensure_ascii=False) + "n"
        self.file.write(line)
        return item
    def spider_closed(self, spider):
        self.file.close()

针对spider里面的utf-8编码格式去掉.encode('utf-8')

item = RecruitItem()
item['name']=name.encode('utf-8')
item['detailLink']=detailLink.encode('utf-8')
item['catalog']=catalog.encode('utf-8')
item['recruitNumber']=recruitNumber.encode('utf-8')
item['workLocation']=workLocation.encode('utf-8')
item['publishTime']=publishTime.encode('utf-8')

将item写入MongoDB

from_crawler(cls, crawler)

如果使用,这类方法被调用创建爬虫管道实例。必须返回管道的一个新实例。crawler提供存取所有Scrapy核心组件配置和信号管理器;对于pipelines这是一种访问配置和信号管理器 的方式。

在这个例子中,我们将使用pymongo将Item写到MongoDB。MongoDB的地址和数据库名称在Scrapy setttings.py配置文件中;

这个例子主要是说明如何使用from_crawler()方法

import pymongo
class MongoPipeline(object):
    collection_name = 'scrapy_items'
    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(
            mongo_uri=crawler.settings.get('MONGO_URI'),
            mongo_db=crawler.settings.get('MONGO_DATABASE', 'items')
        )
    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):
        self.db[self.collection_name].insert(dict(item))
        return item

热门栏目