入坑-乱码

关于爬虫乱码有很多各式各样的问题,这里不仅是中文乱码,编码转换、还包括一些如日文、韩文 、俄文、藏文之类的乱码处理,因为解决方式是一致的,故在此统一说明。

网络爬虫出现乱码的原因

源网页编码和爬取下来后的编码格式不一致。

如源网页为gbk编码的字节流,而我们抓取下后程序直接使用utf-8进行编码并输出到存储文件中,这必然会引起乱码 即当源网页编码和抓取下来后程序直接使用处理编码一致时,则不会出现乱码; 此时再进行统一的字符编码也就不会出现乱码了

注意区分

  • 源网编码A、

  • 程序直接使用的编码B、

  • 统一转换字符的编码C。

乱码的解决方法

确定源网页的编码A,编码A往往在网页中的三个位置

  1. http header的Content-Type

    获取服务器 header 的站点可以通过它来告知浏览器一些页面内容的相关信息。 Content-Type 这一条目的写法就是 "text/html; charset=utf-8"。

  2. meta charset

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
  3. 网页头中Document定义

    <script type="text/javascript">
    if(document.charset){
     alert(document.charset+"!!!!");
     document.charset = 'GBK';
     alert(document.charset);
    }
    else if(document.characterSet){
     alert(document.characterSet+"????");
     document.characterSet = 'GBK';
     alert(document.characterSet);
    }
    

    在获取源网页编码时,依次判断下这三部分数据即可,从前往后,优先级亦是如此。

  4. 以上三者中均没有编码信息 一般采用chardet等第三方网页编码智能识别工具来做

    安装: pip install chardet

    官方网站: http://chardet.readthedocs.io/en/latest/usage.html

Python chardet 字符编码判断

使用 chardet 可以很方便的实现字符串/文件的编码检测 虽然HTML页面有charset标签,但是有些时候是不对的。那么chardet就能帮我们大忙了。

chardet实例

import urllib
rawdata = urllib.urlopen('http://www.jb51.net/').read()
import chardet
chardet.detect(rawdata)
{'confidence': 0.99, 'encoding': 'GB2312'}

chardet可以直接用detect函数来检测所给字符的编码。函数返回值为字典,有2个元素,一个是检测的可信度,另外一个就是检测到的编码。

在开发自用爬虫过程中如何处理汉字编码?

下面所说的都是针对python2.7,如果不加处理,采集到的都是乱码,解决的方法是将html处理成统一的utf-8编码 遇到windows-1252编码,属于chardet编码识别训练未完成

import chardet
a='abc'
type(a)
str
chardet.detect(a)
{'confidence': 1.0, 'encoding': 'ascii'}


a ="我"
chardet.detect(a)
{'confidence': 0.73, 'encoding': 'windows-1252'}
a.decode('windows-1252')
u'\xe6\u02c6\u2018'
chardet.detect(a.decode('windows-1252').encode('utf-8'))
type(a.decode('windows-1252'))
unicode
type(a.decode('windows-1252').encode('utf-8'))
str
chardet.detect(a.decode('windows-1252').encode('utf-8'))
{'confidence': 0.87625, 'encoding': 'utf-8'}


a ="我是中国人"
type(a)
str
{'confidence': 0.9690625, 'encoding': 'utf-8'}
chardet.detect(a)
# -*- coding:utf-8 -*-
import chardet
import urllib2
#抓取网页html
html = urllib2.urlopen('http://www.jb51.net/').read()
print html
mychar=chardet.detect(html)
print mychar
bianma=mychar['encoding']
if bianma == 'utf-8' or bianma == 'UTF-8':
    html=html.decode('utf-8','ignore').encode('utf-8')
else:
    html =html.decode('gb2312','ignore').encode('utf-8')
print html
print chardet.detect(html)

python代码文件的编码

py文件默认是ASCII编码,中文在显示时会做一个ASCII到系统默认编码的转换,这时就会出错:SyntaxError: Non-ASCII character。需要在代码文件的第一行添加编码指示:

# -*- coding:utf-8 -*- 

print '中文'

像上面那样直接输入的字符串是按照代码文件的编码'utf-8'来处理的

如果用unicode编码,以下方式:

s1 = u'中文' #u表示用unicode编码方式储存信息

decode是任何字符串具有的方法,将字符串转换成unicode格式,参数指示源字符串的编码格式。

encode也是任何字符串具有的方法,将字符串转换成参数指定的格式。