scrapy中的Pipeline

当Item在Spider中被收集之后,它将会被传递到Item Pipeline,这些Item Pipeline组件按定义的顺序处理Item。

每个Item Pipeline都是实现了简单方法的Python类,比如决定此Item是丢弃而存储。以下是item pipeline的一些典型应用:

  • 验证爬取的数据(检查item包含某些字段,比如说name字段)
  • 查重(并丢弃)
  • 将爬取结果保存到文件或者数据库中

编写item pipeline

编写item pipeline很简单,item pipiline组件是一个独立的Python类,其中process_item()方法必须实现:

import something

class SomethingPipeline(object):
    def __init__(self):    
        # 可选实现,做参数初始化等
        # doing something

    def process_item(self, item, spider):
        # item (Item 对象) – 被爬取的item
        # spider (Spider 对象) – 爬取该item的spider
        # 这个方法必须实现,每个item pipeline组件都需要调用该方法,
        # 这个方法必须返回一个 Item 对象,被丢弃的item将不会被之后的pipeline组件所处理。
        return item

    def open_spider(self, spider):
        # spider (Spider 对象) – 被开启的spider
        # 可选实现,当spider被开启时,这个方法被调用。

    def close_spider(self, spider):
        # spider (Spider 对象) – 被关闭的spider
        # 可选实现,当spider被关闭时,这个方法被调用

tem写入JSON文件

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

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

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import json

class LoadermanPipeline(object):

    def __init__(self):
        self.file = open('loaderman.json', 'w')
        # self.file.write("[")

    def process_item(self, item, spider):

        jsontext = json.dumps(dict(item), ensure_ascii=False) + " ,\n"

        self.file.write(jsontext.encode("utf-8"))

        return item

    def close_spider(self, spider):
        # self.file.write("]")
        self.file.close()

为了启用Item Pipeline组件,必须将它的类添加到 settings.py文件ITEM_PIPELINES 配置,如下:

# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
#ITEM_PIPELINES = {
#    'scrapyDemo.pipelines.ScrapydemoPipeline': 300,
#}

ITEM_PIPELINES = {

    'scrapyDemo.pipelines.LoadermanPipeline': 300,
}

分配给每个类的整型值,确定了他们运行的顺序,item按数字从低到高的顺序,通过pipeline,通常将这些数字定义在0-1000范围内(0-1000随意设置,数值越低,组件的优先级越高)

重新启动爬虫

将LoadermanSpider中的parse()方法修改代码如下,

# -*- coding: utf-8 -*-
import scrapy

from scrapyDemo.items import LoadermanItem


class LoadermanSpider(scrapy.Spider):
    name = 'loaderman'
    allowed_domains = ['http://www.cnblogs.com']
    start_urls = ['http://www.cnblogs.com/loaderman']

    def parse(self, response):
        # filename = "loaderman.html"
        # open(filename, 'w').write(response.body)
        xpathList = response.xpath("//div[@class='post']")
        # items= []
        for each in xpathList:
            # 将我们得到的数据封装到一个 `LoadermanItem` 对象

            item = LoadermanItem()

            # extract()方法返回的都是unicode字符串
            title = each.xpath(".//h2/a[@class='postTitle2']/text()").extract()
            detailUrl = each.xpath(".//a[@class='postTitle2']/@href").extract()
            content = each.xpath(".//div[@class='c_b_p_desc']/text()").extract()
            date = each.xpath(".//p[@class='postfoot']/text()").extract()
            # xpath返回的是包含一个元素的列表

            item['title'] = title[0]
            item['detailUrl'] = detailUrl[0]
            item['content'] = content[0]
            item['date'] = date[0]
            # items.append(item)
            # #将获取的数据交给pipelines
            yield items

        # 返回数据,不经过pipeline
        # return items

 

然后执行下面的命令:

scrapy crawl loaderman

 

查看当前目录是否生成loaderman.json

posted on 2019-12-07 13:46  LoaderMan  阅读(407)  评论(0编辑  收藏  举报

导航