Item Pipeline

    每个item pipeline组件(有时称之为“Item Pipeline”)是实现了简单方法的Python类。他们接收到Item并通过它执行一些行为,同时也决定此Item是否继续通过pipeline,或是被丢弃而不再进行处理。

    以下是item pipeline的一些典型应用:

    • 验证爬取的数据(检查item包含某些字段)
    • 查重(并丢弃)
    • 将爬取结果保存到数据库中

    每个item pipiline组件是一个独立的Python类,同时必须实现以下方法:

    (_self, item, spider)

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



    此外,他们也可以实现以下方法:
    (_self, spider)

    当spider被开启时,这个方法被调用。


    closespider(_self, spider)

    当spider被关闭时,这个方法被调用


    fromcrawler(_cls, crawler)

    If present, this classmethod is called to create a pipeline instancefrom a . It must return a new instanceof the pipeline. Crawler object provides access to all Scrapy corecomponents like settings and signals; it is a way for pipeline toaccess them and hook its functionality into Scrapy.


    让我们来看一下以下这个假设的pipeline,它为那些不含税(price_excludes_vat 属性)的item调整了 price 属性,同时丢弃了那些没有价格的item:

    注解

    JsonWriterPipeline的目的只是为了介绍怎样编写item pipeline,如果你想要将所有爬取的item都保存到同一个JSON文件,你需要使用 。

    In this example we’ll write items to MongoDB using .MongoDB address and database name are specified in Scrapy settings;MongoDB collection is named after item class.

    The main point of this example is to show how to use method and how to clean up the resources properly.

    Previous example (JsonWriterPipeline) doesn’t clean up resources properly.Fixing it is left as an exercise for the reader.

    一个用于去重的过滤器,丢弃那些已经被处理过的item。让我们假设我们的item有一个唯一的id,但是我们spider返回的多个item中包含有相同的id:

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

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