自定义Pipeline输出json文件
代码
class JsonWithEncodingPipeline(object):
#自定义json文件的导出
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()
写好pipeline后记得在settings中将这个pipeline设置进去。
测试代码
def test_to_json():
import codecs
import json
# 自定义json文件的导出
file = codecs.open('test.json', 'w', encoding="utf-8")
item = {'张三': 32, 'Jim': 23, 'Bob': 53}
# lines = json.dumps(item, ensure_ascii=False) + "\n"
lines = json.dumps(item) + "\n"
file.write(lines)
file.close()
测试结果
数据:{‘张三’: 32, ‘Jim’: 23, ‘Bob’: 53}
lines = json.dumps(item,ensure_ascii=False) + “\n”
- 添加参数ensure_ascii=False:
输出本地文件test.json: {“张三”: 32, “Jim”: 23, “Bob”: 53} - 不添加参数ensure_ascii=False:
输出本地文件test.json: {"\u5f20\u4e09": 32, “Jim”: 23, “Bob”: 53}
测试分析
json.dumps()将python数据序列化到本地过程中,默认使用ascii编码格式,中文如果想正常导出,则需要添加参数:ensure_ascii=False,取消ascii默认编码方式。
json包
参考Python 标准库-json
里面有对json库的使用说明。
- json.loads():字符串–>python基本数据类型
- json.dumps():python基本数据类型–>字符串
- json.load():文件–>python基本数据类型
- json.dump():python基本数据类型–>文件
利用Scrapy提供的JsonItemExporter类保存json数据
示例代码
class JsonExporterPipleline(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 close_spider(self, spider):
self.exporter.finish_exporting()
self.file.close()
def process_item(self, item, spider):
self.exporter.export_item(item)
return item
总结
使用JsonItemExporter对象前需要先实例化该对象以及其参数,使用过程中需要有以下步骤:
- 调用方法start_exporting()以标识exporting过程的开始。
- 对要导出的每个项目调用export_item()方法。
- 最后调用finish_exporting()表示exporting过程的结束。