scrapy避免直接输出unicode

我们使用scrapy crawl xxx -o xxx.json时,scrapy时直接输出unicode格式

解决方案


1.pipeline中对items进一步处理


class FinancePipeline(object):
    def __init__(self):
        self.file = codecs.open('../../data/ftchinese/ftchinese.json', 'w', encoding='utf-8')
        self.file.write('[')
    def process_item(self, item, spider):
        line = json.dumps(dict(item), ensure_ascii=False) + ",\n"
        self.file.write(line)
        return item
    def close_spider(self, spider):
        position = self.file.tell()
        print('position = %s' % position)
        self.file.write(']')
        self.file.close()


2.自定义export


查找了官方doc,确实可以自定义,默认的有一下




我们来自定义


# 定义ensure_ascii=False,避免直接输出unicode
from scrapy.exporters import JsonLinesItemExporter
class CustomJsonLinesItemExporter(JsonLinesItemExporter):
    def __init__(self, file, **kwargs):
        super(CustomJsonLinesItemExporter, self).__init__(file, ensure_ascii=False, **kwargs)

FEED_EXPORTERS = {
    'json': 'finance.settings.CustomJsonLinesItemExporter',
}


测试

 'start_time': datetime.datetime(2016, 9, 29, 1, 49, 8, 317000)}
2016-09-29 09:49:09 [scrapy] INFO: Spider closed (finished)

d:\repo\WeBot\scrapy\finance>scrapy crawl economy -o test.json


{"content": "人们的悲观情绪越来越强烈之际,随着全球经济增长前景变得黯淡(尤其是中国经济放缓带来不确定性),股市今年出现了极为糟糕的开局,标普500(S&P 500)指数出现了大幅波动。", "current_time": "Thu Sep 29 09:49:09 2016", "original_time": "2016年2月29日", "title": "美国企业首季盈利预测遭下调"}
{"content": "与相关磋商关系密切的人士表示,中国已在催促下重新拟定其主权债合同,以反映出对一种新融资框架的支持。这种美国政府支持的新融资框架旨在改善政府与债权人间的关系。", "current_time": "Thu Sep 29 09:49:09 2016", "original_time": "2016年4月11日", "title": "中国拟改革主权债发行体制"}
{"content": "财新在同时发布的一份声明中表示:“虽然仍低于50.0临界值,但已是13个月来最高纪录,显示制造业运行只是轻微放缓。", "current_time": "Thu Sep 29 09:49:09 2016", "original_time": "2016年4月1日", "title": "3月份财新制造业PMI强于预期"}
{"content": "3月份,中国官方制造业购经理指数(PMI)为50.2,而经济学家的预期为49.4,2月份的读数则为49。读数高于50,代表制造业活动处于扩张之中。", "current_time": "Thu Sep 29 09:49:09 2016", "original_time": "2016年4月1日", "title": "3月份中国官方制造业PMI为50.2"}



  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值