![](https://img.haomeiwen.com/i1920664/e6ab07ac726900dc.jpg)
- scrapy crawl musicspide -o mu.json 方式是框架为我们提供的一种数据存储方式,但是更多的是我们自定义的处理,爬虫在爬取数据后保存及后期处理就交给pipelines管道来实现。
- 在pipelines.py写入:
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
#管道负责item后期保存
class MyspiderPipeline(object):
def __init__(self):#定义一些初始化的参数可以省略
self.file=open('music.txt','a')
#管道每次接收item后,执行下面的方法
def process_item(self, item, spider):
content=str(item)+'\n'
self.file.write(content)
return item
#当爬虫爬取结束时执行的方法
def close_spider(self,spider):
self.file.close()
- 在用scrapy crawl musicspider 之前,我们需要将setting.py文件中的部分代码注释取消掉,在69行左右的管道部分取消注释,300代表优先级的默认值,它的范围为0-1000,由于我们只有一个管道,因此不做改动。
![](https://img.haomeiwen.com/i1920664/2e6a7ab22cc74b2f.png)
在黑屏终端中输入scrapy crawl musicspider 结果:
![](https://img.haomeiwen.com/i1920664/f42dc52d4829290f.png)
网友评论