美文网首页爬虫学习
爬虫scrapy框架(5)——pipelines

爬虫scrapy框架(5)——pipelines

作者: 猛犸象和剑齿虎 | 来源:发表于2019-05-30 06:38 被阅读0次
t013b9c86f5a43c0037.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,由于我们只有一个管道,因此不做改动。
image.png

在黑屏终端中输入scrapy crawl musicspider 结果:


image.png

相关文章

网友评论

    本文标题:爬虫scrapy框架(5)——pipelines

    本文链接:https://www.haomeiwen.com/subject/gxhqtctx.html