Python网络爬虫出现乱码问题的解决方法
关于爬虫乱码有很多各式各样的问题,这里不仅是中文乱码,编码转换、还包括一些如日文、韩文 、俄文、藏文之类的乱码处理,因为解决方式是一致的,故在此统一说明。 网络爬虫出现乱码的原因 源网页编码和爬取下来后的编码格式不一致。 注意区分
乱码的解决方法 确定源网页的编码A,编码A往往在网页中的三个位置 1.http header的Content-Type 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); } 在获取源网页编码时,依次判断下这三部分数据即可,从前往后,优先级亦是如此。 安装: pip install chardet 官方网站: http://chardet.readthedocs.io/en/latest/usage.html Python chardet 字符编码判断 使用 chardet 可以很方便的实现字符串/文件的编码检测 虽然HTML页面有charset标签,但是有些时候是不对的。那么chardet就能帮我们大忙了。 import urllib rawdata = urllib.urlopen('http://www.aspzz.cn/').read() import chardet chardet.detect(rawdata) {'confidence': 0.99,'encoding': 'GB2312'} chardet可以直接用detect函数来检测所给字符的编码。函数返回值为字典,有2个元素,一个是检测的可信度,另外一个就是检测到的编码。 在开发自用爬虫过程中如何处理汉字编码? 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'xe6u02c6u2018' 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.aspzz.cn/').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代码文件的编码 # -*- coding:utf-8 -*- print '中文' 像上面那样直接输入的字符串是按照代码文件的编码'utf-8'来处理的 s1 = u'中文' #u表示用unicode编码方式储存信息 decode是任何字符串具有的方法,将字符串转换成unicode格式,参数指示源字符串的编码格式。 更多内容请参考专题《python爬取功能汇总》进行学习。 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。 您可能感兴趣的文章:
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |