注意:此方法跟之前保存成json文件的写法有少许不同之处,注意区分
情境再现:
使用scrapy抓取中文网页,得到的数据类型是unicode,在控制台输出的话也是显示unicode,如下所示
{'author': u'u51afu53cbu5170u7b49',
'classification': u' u4ebau6587u793eu79d1',
'down_bd_code': u'u63d0u53d6u5bc6u7801uff1asp6t',
'down_bd_url': u'https://pan.baidu.com/s/1N1NPVupmnPX6W5Fm2YHccg',
'title': u'u4e2du897fu65b9u54f2u5b66u53f2uff08u5957u88c5u51712u518cuff09'}
保存成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) + ' ' 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文件