scrapy抓取的頁面中文會變成unicode字符串


不了解編碼的,需要先補下:http://www.cnblogs.com/jiangtu/p/6245264.html

在學習&使用scrapy抓取網上信息時,發現scrapy 會將含有中文的field輸出為 unicode字符串形式。

這個原因的根本是,在python中使用json序列化時,如果使用 ensure_ascii 編碼就會出現這個問題。並且,json.dumps默認使用的也是這個編碼。

在scrapy中,JsonItemExporter 也是默認使用的 ensure_ascii 編碼:

1 class JsonItemExporter(BaseItemExporter):
2 
3     def __init__(self, file, **kwargs):
4         self._configure(kwargs, dont_fail=True)
5         self.file = file
6         kwargs.setdefault('ensure_ascii', not self.encoding) # look here 7         self.encoder = ScrapyJSONEncoder(**kwargs)
8         self.first_item = True

可以看到,在第六行,如果不傳遞值的話,就會默認使用 ensure_ascii 編碼。

所以,我們只要在 pipeline 中實例化 exporter 時,傳入編碼方式即可:

exporter = MyJsonExporter(fi, encoding='utf-8')

然后就ok了。

JSON.dumps()同理。

 


免責聲明!

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



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