清理HTML数据
验证爬取的数据(检查item包含某些字段)
查重(并丢弃)
将爬取结果保存到数据库中
样例:让我们来看一下以下这个假设的pipeline,它为那些不含税(price_excludes_vat
属性)的item调整了price
属性,同时丢弃了那些没有价格的item:
from scrapy.exceptions import DropItem class PricePipeline(object): vat_factor = 1.15 //定义属性 def process_item(self, item, spider): //定义方法 if item['price']: //判断price 是否存在 if item['price_excludes_vat']: //判断price_excludes_vat是否存在 item['price'] = item['price'] * self.vat_factor //存在执行的操作 return item //返回 else: raise DropItem("Missing price in %s" % item) //如果不存在 ,触发异常
以下pipeline将所有(从所有spider中)爬取到的item,存储到一个独立地 items.jl
文件,每行包含一个序列化为JSON格式的item:
import jsonclass JsonWriterPipeline(object): def __init__(self): self.file = open('items.jl', 'wb') def process_item(self, item, spider): line = json.dumps(dict(item)) + "\n" self.file.write(line) return item
In this example we’ll write items to MongoDB using pymongo. MongoDB address and database name are specified in Scrapy settings; MongoDB collection is named after item class.
在这个例子中,我们将要使用pymongo把items写入MogoDB中,MongoDB的地址和库名是在Scrapy settings中指定。MongoDB 集合是被命名在item类后。
The main point of this example is to show how to use from_crawler()
method and how to clean up the resources properly.
这个例子的主要点是用来显示怎样使用from_crawler()
方法和怎么恰当的清理源文件。
注解
Previous example (JsonWriterPipeline) doesn’t clean up resources properly. Fixing it is left as an exercise for the reader.
上面的例子(JsonWriterPipeline) 不能恰当的清理资源,处理它作为一个练习。
import pymongoclass 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
一个用于去重的过滤器,丢弃那些已经被处理过的item。让我们假设我们的item有一个唯一的id,但是我们spider返回的多个item中包含有相同的id:
from scrapy.exceptions import DropItemclass DuplicatesPipeline(object): def __init__(self): self.ids_seen = set() def process_item(self, item, spider): if item['id'] in self.ids_seen: raise DropItem("Duplicate item found: %s" % item) else: self.ids_seen.add(item['id']) return item
为了启用一个Item Pipeline组件,你必须将它的类添加到 ITEM_PIPELINES
配置,就像下面这个例子:
ITEM_PIPELINES = { 'myproject.pipelines.PricePipeline': 300, 'myproject.pipelines.JsonWriterPipeline': 800,}
分配给每个类的整型值,确定了他们运行的顺序,item按数字从低到高的顺序,通过pipeline,通常将这些数字定义在0-1000范围内。数字是优先级。