如何将Item保存成json文件

现在只是学到这么写,为什么这样写还得继续学习

方法一,在pipelines.py中自定义的自己的json类

class JsonWithEncodingPipeline(object):
    def __init__(self):
        self.file = codecs.open('article.json', 'w', encoding="utf-8")
    def process_item(self, item, spider):
        lines = json.dumps(dict(item), ensure_ascii=False) + "\n"#确保中文显示正常
        self.file.write(lines)
        return item
    def spider_closed(self, spider):
        self.file.close()
然后在settings.py中将其写入ITEM_PIPELINES函数中

'ArticleSpider.pipelines.JsonWithEncodingPipeline': 2
运行main.py,成功。

另一种是scrapy自带的将item转换成各种类型文件保存。

发现scrapy中可以将item转化成上述文件保存,例如Csv,Xml.

class JsonExporterPipeline(object):
    #调用scrapy提供的json export 导出json文件
    def __init__(self):
        self.file = open('articleexport.json', 'wb')
        self.exporter = JsonItemExporter(self.file, encoding = "utf-8", ensure_ascii=False)
        self.exporter.start_exporting()

    def process_item(self, item, spider):
        self.exporter.export_item(item)
        return item

    def close_spider(self,spider):
        self.exporter.finish_exporting()

再到setting.py中修改ITEM_PIPELINES

'ArticleSpider.pipelines.JsonExporterPipeline': 2


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值