zoukankan      html  css  js  c++  java
  • Scrapy研究探索(四)——中文输出与中文保存

    提取网页中中文并输出或者是保存时经常会出现一个问题是显示的是中文对应的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. xe4xbdxbfxe7x94xa8  


    这是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

  • 相关阅读:
    第一课 进阶高手的大门
    Codeforces Round #363 (Div. 2) C. Vacations
    HDU 5718 Oracle
    A
    Fibonacci数的后9位
    UESTC 982质因子分解
    UESTC149 解救小Q
    UESTC93 King's Sanctuary
    HDU 4857 逃生
    L1-006. 连续因子
  • 原文地址:https://www.cnblogs.com/lmsj/p/6504730.html
Copyright © 2011-2022 走看看