在scrapy创建成功后,在自动生成的目录中会有items.py文件和pipelines.py文件,这两个都是可以用来保存文件的。下面就来写一下这两个文件的保存文件的方式。
title = scrapy.Field()
- item = AncientPoemsItem()
- item['title'] = response.xpath('//div[@class="left"]/div[@class="sons"]/div[*].a[2]/text()').get()
scrapy crawl app -o app.json
app是爬虫名字,-o表示使用items.py文件进行保存,app.json表示保存后的名字和格式。并且该命令支持以下的格式:
json、jsonlines、jl、csv、xml、marshal、pickle
该文件又被称为项目管道,在一个项目被蜘蛛抓取之后,它被发送到项目管道,该管道通过几个按顺序执行的组件来处理它。每个项管道组件(有时称为“项管道”)都是一个实现简单方法的Python类。必须实现以下方法:
此外,它们还可以实现以下方法:
参数crawler表示使用此管道的爬虫程序
以下就使用该文件将数据保存到MoggoDb数据库中为例
第一步:在settings.py文件中设置连接参数
- MONGO_URI = "127.0.0.1" # 数据库地址
- MONGO_DATABASE = "古诗词" # 需要保存到哪个的数据库名
第二步:编写项目管道
- class MongoPipeline:
- collection_name = 'scrapy_items' # 数据库集合名
-
- # 从settings文件中获取参数,并交由__init中进行参数化
- @classmethod
- def from_crawler(cls, crawler):
- return cls(
- mongo_uri=crawler.settings.get('MONGO_URI'),
- mongo_db=crawler.settings.get('MONGO_DATABASE')
- )
-
- # 初始化参数
- def __init__(self, mongo_uri, mongo_db):
- self.mongo_uri = mongo_uri
- self.mongo_db = mongo_db
-
- # 连接数据库
- def open_spider(self, spider):
- self.client = pymongo.MongoClient(self.mongo_uri)
- self.db = self.client[self.mongo_db]
-
- # 对数据进行保存
- def process_item(self, item, spider):
- self.db[self.collection_name].insert_one(dict(item))
- return item
-
- # 关闭和数据库的连接
- def close_spider(self, spider):
- self.client.close()
第三步:开启项目管道
在settings.py文件中
- ITEM_PIPELINES = {
- 'Ancient_poems.pipelines.MongoPipeline': 300,
- }
键名为项目管道的类名,值为一个数字,数字越大,表示该管道被调用的优先级越低,一般该数字定义为0-1000范围内。