Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / Python处理中文编码和判断编码

在开发自用爬虫过程中,有的网页是utf-8,有的是gb2312,有的是gbk,如果不加处理,采集到的都是乱码,解决的方法是将html处理成统一的utf-8编码针对python2.7。代码如下:#coding:utf-8
#chardet 需要下载安装
import chardet
#抓取网页html
line = "http://www.linuxidc.com"
html_1 = urllib2.urlopen(line,timeout=120).read()
#print html_1
encoding_dict = chardet.detect(html_1)
#print encoding
web_encoding = encoding_dict["encoding"]
if web_encoding == "utf-8" or web_encoding == "UTF-8":html = html_1
else :
html = html_1.decode("gbk","ignore").encode("utf-8")
#有以上处理,整个html就不会是乱码。Python解析xml文档实例  http://www.linuxidc.com/Linux/2012-02/54760.htm《Python核心编程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm《Python开发技术详解》.( 周伟,宗杰).[高清PDF扫描版+随书视频+代码] http://www.linuxidc.com/Linux/2013-11/92693.htmPython脚本获取Linux系统信息 http://www.linuxidc.com/Linux/2013-08/88531.htm在Ubuntu下用Python搭建桌面算法交易研究环境 http://www.linuxidc.com/Linux/2013-11/92534.htmPython 语言的发展简史 http://www.linuxidc.com/Linux/2014-09/107206.htmPython 的详细介绍:请点这里
Python 的下载地址:请点这里本文永久更新链接地址:http://www.linuxidc.com/Linux/2015-01/111134.htm