scrapy相关 通过设置 FEED_EXPORT_ENCODING 解决 unicode 中文写入json文件出现`\uXXXX`
0.问题现象
爬取 item:
2017-10-16 18:17:33 [scrapy.core.scraper] DEBUG: Scraped from <200 https://www.huxiu.com/v2_action/article_list>
{'author': u'\u5546\u4e1a\u8bc4\u8bba\u7cbe\u9009\xa9',
'cmt': 5,
'fav': 194,
'time': u'4\u5929\u524d',
'title': u'\u96f7\u519b\u8c08\u5c0f\u7c73\u201c\u65b0\u96f6\u552e\u201d\uff1a\u50cfZara\u4e00\u6837\u5f00\u5e97\uff0c\u8981\u505a\u5f97\u6bd4Costco\u66f4\u597d',
'url': u'/article/217755.html'}
写入jsonline jl 文件
{"title": "\u8fd9\u4e00\u5468\uff1a\u8d2b\u7a77\u66b4\u51fb", "url": "/article/217997.html", "author": "\u864e\u55c5", "fav": 8, "time": "2\u5929\u524d", "cmt": 5}
{"title": "\u502a\u840d\u8001\u516c\u7684\u65b0\u620f\u6251\u8857\u4e86\uff0c\u9ec4\u6e24\u6301\u80a1\u7684\u516c\u53f8\u8981\u8d54\u60e8\u4e86", "url": "/article/217977.html", "author": "\u5a31\u4e50\u8d44\u672c\u8bba", "fav": 5, "time": "2\u5929\u524d", "cmt": 3}
item 被转 str,默认 ensure_ascii = True,则非 ASCII 字符被转化为 `\uXXXX`,每一个 ‘{xxx}’ 单位被写入文件
目标:注意最后用 chrome 或 notepad++ 打开确认,firefox 打开 jl 可能出现中文乱码,需要手动指定编码。
{"title": "这一周:贫穷暴击", "url": "/article/217997.html", "author": "虎嗅", "fav": 8, "time": "2天前", "cmt": 5}
{"title": "倪萍老公的新戏扑街了,黄渤持股的公司要赔惨了", "url": "/article/217977.html", "author": "娱乐资本论", "fav": 5, "time": "2天前", "cmt": 3}
1.参考资料
scrapy抓取到中文,保存到json文件为unicode,如何解决.
import json
import codecs class JsonWithEncodingPipeline(object): def __init__(self):
self.file = codecs.open('scraped_data_utf8.json', 'w', encoding='utf-8') def process_item(self, item, spider):^M
line = json.dumps(dict(item), ensure_ascii=False) + "\n"
self.file.write(line)
return item def close_spider(self, spider):
self.file.close()
Scrapy爬虫框架抓取中文结果为Unicode编码,如何转换UTF-8编码
以上资料实际上就是官方文档举的 pipeline 例子,另外指定 ensure_ascii=False
Write items to a JSON file
The following pipeline stores all scraped items (from all spiders) into a single items.jl file, containing one item per line serialized in JSON format:
import json
class JsonWriterPipeline(object):
def open_spider(self, spider):
self.file = open('items.jl', 'w')
def close_spider(self, spider):
self.file.close()
def process_item(self, item, spider):
line = json.dumps(dict(item)) + "\n" #另外指定 ensure_ascii=False
self.file.write(line)
return item
Note
The purpose of JsonWriterPipeline is just to introduce how to write item pipelines. If you really want to store all scraped items into a JSON file you should use the Feed exports.
2.更好的解决办法:
scrapy 使用item export输出中文到json文件,内容为unicode码,如何输出为中文?
http://stackoverflow.com/questions/18337407/saving-utf-8-texts-in-json-dumps-as-utf8-not-as-u-escape-sequence 里面有提到,将 JSONEncoder 的 ensure_ascii 参数设为 False 即可。
而 scrapy 的 item export 文档里有提到
The additional constructor arguments are passed to the
BaseItemExporter constructor, and the leftover arguments to the
JSONEncoder constructor, so you can use any JSONEncoder constructor
argument to customize this exporter.
因此就在调用 scrapy.contrib.exporter.JsonItemExporter 的时候额外指定 ensure_ascii=False 就可以啦。
3.根据上述解答,结合官网和源代码,直接解决办法:
1.可以通过修改 project settings.py 补充 FEED_EXPORT_ENCODING = 'utf-8'
2.或在cmd中传入 G:\pydata\pycode\scrapy\huxiu_com>scrapy crawl -o new.jl -s FEED_EXPORT_ENCODING='utf-8' huxiu
https://doc.scrapy.org/en/latest/topics/feed-exports.html#feed-export-encoding
FEED_EXPORT_ENCODING
Default: None
The encoding to be used for the feed.
If unset or set to None (default) it uses UTF-8 for everything except JSON output, which uses safe numeric encoding (\uXXXX sequences) for historic reasons.
Use utf-8 if you want UTF-8 for JSON too.
In [615]: json.dump?
Signature: json.dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, sort_keys=False, **kw)
Docstring:
Serialize ``obj`` as a JSON formatted stream to ``fp`` (a
``.write()``-supporting file-like object). If ``ensure_ascii`` is true (the default), all non-ASCII characters in the
output are escaped with ``\uXXXX`` sequences, and the result is a ``str``
instance consisting of ASCII characters only. If ``ensure_ascii`` is
``False``, some chunks written to ``fp`` may be ``unicode`` instances.
This usually happens because the input contains unicode strings or the
``encoding`` parameter is used. Unless ``fp.write()`` explicitly
understands ``unicode`` (as in ``codecs.getwriter``) this is likely to
cause an error.
C:\Program Files\Anaconda2\Lib\site-packages\scrapy\exporters.py
class JsonLinesItemExporter(BaseItemExporter):
def __init__(self, file, **kwargs):
kwargs.setdefault('ensure_ascii', not self.encoding)
class JsonItemExporter(BaseItemExporter):
def __init__(self, file, **kwargs):
kwargs.setdefault('ensure_ascii', not self.encoding)
class XmlItemExporter(BaseItemExporter):
def __init__(self, file, **kwargs):
if not self.encoding:
self.encoding = 'utf-8'
scrapy相关 通过设置 FEED_EXPORT_ENCODING 解决 unicode 中文写入json文件出现`\uXXXX`的更多相关文章
- python 数据写入json文件时中文显示Unicode编码问题
一.问题描述 import json dir = { '春晓':'asfffa', '春眠不觉晓' : '处处闻啼鸟', '夜来风雨声' : 56789, 'asdga':'asdasda' } fp ...
- 设置webconfig 解决asp.net上传文件过大问题
对于asp.net,默认只允许上传4M文件,增加如下配置,一般可以自定义最大文件大小. <httpRuntime executionTimeout="800" maxRequ ...
- php 如何把中文写入json中 当json文件中还显示的是中文
/*** * 更新版本 */ function showupversionsub(){ #接受post 过来的数据 $app_type=$_POST['aap_type']; if($app_type ...
- scrapy基础知识之将item写入JSON文件:
pipelines.py import json class xxPipeline(object): def __init__(self): self.filename=ope ...
- scrapy抓取到中文,保存到json文件为unicode,如何解决.
http://scrapy-chs.readthedocs.org/zh_CN/latest/intro/overview.html 以上链接是很好的scrapy学些资料.感谢marchtea的翻译. ...
- Android开发教程 - 使用Data Binding Android Studio不能正常生成相关类/方法的解决办法
本系列目录 使用Data Binding(一)介绍 使用Data Binding(二)集成与配置 使用Data Binding(三)在Activity中的使用 使用Data Binding(四)在Fr ...
- python3写入csv文件时中文为乱码
今天修改李万的爬虫时把页面上的中文写入csv文件时,中文总是乱码.通过上网搜索得到解决.解决的办法是打开文件是需加参数 encoding='utf-8-sig' .感谢博客园的菜鸟Alex.他相关博客 ...
- 解决Scrapy抓取中文网页保存为json文件时中文不显示而是显示unicode的问题
注意:此方法跟之前保存成json文件的写法有少许不同之处,注意区分 情境再现: 使用scrapy抓取中文网页,得到的数据类型是unicode,在控制台输出的话也是显示unicode,如下所示 {'au ...
- 解决 git 中文路径显示 unicode 代码的问题
解决 git 中文路径显示 unicode 代码的问题 当被修改的文件中带有中文字符时,中文字符会被转换为 unicode 代码,看不出原来的文件名. 这时,只要配置 :: git config -- ...
随机推荐
- MySQL——设置库中的表以奇数自增
语句 SHOW VARIABLES LIKE 'auto_inc%'; 查看auto_increment_increment的值是不是1,如果是就设置成2 ; 这样所有的表都会以奇数来自增了,因为这个 ...
- 【XSY2903】B 莫比乌斯反演
题目描述 有一个\(n\times n\)的网格,除了左下角的格子外每个格子的中心里都有一个圆,每个圆的半径为\(R\),问你在左下角的格子的中心能看到多少个圆. \(n\leq {10}^9,R_0 ...
- [九省联考2018]IIIDX
题目描述 这一天,Konano接到了一个任务,他需要给正在制作中的游戏<IIIDX>安排曲目的解锁顺序.游戏内共有n首曲目 ,每首曲目都会有一个难度d,游戏内第i首曲目会在玩家Pass第t ...
- JDK动态代理(Proxy)的两种实现方式
JDK自带的Proxy动态代理两种实现方式 前提条件:JDK Proxy必须实现对象接口 so,创建一个接口文件,一个实现接口对象,一个动态代理文件 接口文件:TargetInterface.java ...
- 配置sudo记录日志
sudosudo命令用来以其他身份来执行命令,预设的身份为root.在/etc/sudoers中设置了可执行sudo指令的用户.若其未经授权的用户企图使用sudo,则会发出警告的邮件给管理员.用户使用 ...
- AGC027B Garbage Collector
一道很好的构造题 原题链接 很快就能想到,捡每个垃圾的能量可以最后再算.然后,对于每个垃圾,在路上耗费的能量仅与它是第几个被捡的有关,于是我们考虑将垃圾分组. 首先,我们定义\(F(x,i)\)为某次 ...
- EXCEL(1)级联下拉框
EXCEL级联下拉框 http://jingyan.baidu.com/article/3c343ff756e0cf0d377963f9.html 在输入一些多级项目时,如果输入前一级内容后,能够自动 ...
- windows上编译zlib-1.2.8
MSVC编译 使用VS(x86)命令行工具进入到zlib根目录,执行 nmake -f win32/Makefile.msc ,在根目录下生成:zlib.lib(静态库) zdll.lib(动态库的 ...
- freemarker和thymeleaf的使用样例
最近需要对公司项目首页使用Java模板重做,以提高首屏加载速度和优化SEO. 在选择模板时发现freemarker和thymeleaf最为常用. 两者最大的区别在于语法,对性能方面未作测试,具体性能测 ...
- 利用pyinstaller 打包Python文件
1.下载安装pyinstaller模块 cmd 命令: pip install pyinstaller cmd命令: pip list 查看自己安装的模块 2.建议把要大包的Python文件单独放到新 ...