注意: 此方法跟之前保存成 JSON 文件的写法有少许不同之处, 注意区分
情境再现:
使用 scrapy 抓取中文网页, 得到的数据类型是 unicode, 在控制台输出的话也是显示 unicode, 如下所示
- {
- 'author': u'\u51af\u53cb\u5170\u7b49',
- 'classification': u'\u4eba\u6587\u793e\u79d1',
- 'down_bd_code': u'\u63d0\u53d6\u5bc6\u7801\uff1asp6t',
- 'down_bd_url': u'https://pan.baidu.com/s/1N1NPVupmnPX6W5Fm2YHccg',
- 'title': u'\u4e2d\u897f\u65b9\u54f2\u5b66\u53f2\uff08\u5957\u88c5\u51712\u518c\uff09'
- }
保存成 JSON 文件时需要显示出中文
- import JSON
- import codecs
- # Define your item pipelines here
- #
- # Don't forget to add your pipeline to the ITEM_PIPELINES setting
- # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
- class WriteJsonPipeline(object):
- def __init__(self):
- self.file = codecs.open('items.json', 'w', encoding='utf-8')
- def process_item(self, item, spider):
- line = JSON.dumps(dict(item),ensure_ascii=False) + '\n'
- self.file.write(line)
- return item
- def spider_closed(self, spider):
- self.file.close()
将以上内容插入 pipelines.py, 同时在 settings.py 中加入
- ITEM_PIPELINES = {
- 'panda.pipelines.WriteJsonPipeline': 300
- }
以调用 pipelines 文件
来源: http://www.bubuko.com/infodetail-2931176.html