scrapy抓取到中文,保存到json文件為unicode,如何解決.


http://scrapy-chs.readthedocs.org/zh_CN/latest/intro/overview.html

以上鏈接是很好的scrapy學些資料.感謝marchtea的翻譯.

在學習過程中,碰到一個很棘手的問題: 中文的顯示和存儲. (中文在控制台顯示的為\u77e5\u540d...這樣的字符,保存到文件也是這樣的)

在網上找了很久,下面這個鏈接應是最切題的.

http://stackoverflow.com/questions/9181214/scrapy-text-encoding

摘抄如下:

pipelines.py:

 1 import json
 2 import codecs
 3 
 4 class JsonWithEncodingPipeline(object):
 5 
 6     def __init__(self):
 7         self.file = codecs.open('scraped_data_utf8.json', 'w', encoding='utf-8')
 8 
 9     def process_item(self, item, spider):
10         line = json.dumps(dict(item), ensure_ascii=False) + "\n"
11         self.file.write(line)
12         return item
13 
14     def spider_closed(self, spider):
15         self.file.close()

按照上面的方法,輸出到文件就是正常的中文了.

 我的測試代碼

搜索關鍵字和鏈接:
JsonItemExporter ensure_ascii=False
JsonItemExporter uxxx
python輸出json文件\uxxx如何轉換成中文
Decode and Encode in Python [ http://yangpengg.github.io/blog/2012/12/13/decode-and-encode-in-python/ ]
--
python print輸出的是中文但是輸出到文件的是\uxxx
http://wklken.me/posts/2013/08/31/python-extra-coding-intro.html

Scrapy : storing the data
http://stackoverflow.com/questions/14073442/scrapy-storing-the-data

scrapy 使用item export輸出中文到json文件,內容為unicode碼,如何輸出為中文?
http://www.lefern.com/question/15837/scrapy-shi-yong-item-exportshu-chu-zhong-wen-dao-jsonwen-jian-nei-rong-wei-unicodema-ru-he-shu-chu-wei-zhong-wen/

how to put in json utf-8 symbols, not their codes?
https://groups.google.com/forum/#!msg/scrapy-users/rJcfSFVZ3O4/ZYsD7CMoCKMJ

scrapy text encoding
http://stackoverflow.com/questions/9181214/scrapy-text-encoding

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM