代码改变世界

Scrapy研究探索(四)——中文输出与中文保存

2017-03-05 11:35  小宇15561566132  阅读(188)  评论(0)    收藏  举报

提取网页中中文并输出或者是保存时经常会出现一个问题是显示的是中文对应的unicode编码而非中文本身,这里讲述解决这种问题的方法。

 
 

一. 针对交互输出。

如以下代码:

 

[python] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. title = site.xpath('a/text()').extract()  
  2. link = site.xpath('a/@href').extract()  
  3. desc = site.xpath('a/@title').extract()  
[python] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. print title  


此时title的输出可能是类似于如下:

 

 

[python] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. \xe4\xbd\xbf\xe7\x94\xa8  


这是title对应中文的unicode格式。

 

将其转换为utf-8在输出即可:

 

[python] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. title = site.xpath('a/text()').extract()  
  2. link = site.xpath('a/@href').extract()  
  3. desc = site.xpath('a/@title').extract()  
  4.   
  5. print title  
  6. for t in title:  
  7.     print t.encode('utf-8')  

 

 

这时两次输出的前一次为unicode码,而后一次为中文。

注意:

encode()只针对str数据结构,如果不是,可以先转换为str。上面由于得到的title为list类型,所以转换如上。

二. 针对存储。

关于存储,可查看在教程(二)(http://blog.csdn.net/u012150179/article/details/32911511)中在w3school和pipelines中使用的方式达到保存中文的效果。

转自:http://blog.csdn.net/u012150179/article/details/34450547