Chinaunix首页 | 论坛 | 博客
  • 博客访问: 337500
  • 博文数量: 148
  • 博客积分: 2745
  • 博客等级: 少校
  • 技术积分: 1704
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-30 14:59
文章分类

全部博文(148)

文章存档

2013年(97)

2012年(7)

2011年(3)

2010年(41)

我的朋友

分类: Python/Ruby

2013-06-04 22:02:54

我们经常通过的时候,会碰到一些乱码问题,今天给大家分享一个解决网页乱码,尤其是中文网页的通用方法。

首页我们需要安装chardet模块,这个可以通过easy_install 或者pip来安装。

安装完以后我们在控制台上导入模块,如果正常就可以。

比如我们遇到的一些ISO-8859-2也是可以通过下面的方法解决的。

直接上代码吧:

import urllib2
import sys
import chardet

req = urllib2.Request("")##这里可以换成
content = urllib2.urlopen(req).read()
typeEncode = sys.getfilesystemencoding()##系统默认编码
infoencode = chardet.detect(content).get('encoding','utf-8')##通过第3方模块来自动提取网页的编码
html = content.decode(infoencode,'ignore').encode(typeEncode)##先转换成unicode编码,然后转换系统编码输出
print html

 通过上面的代码,相信能够解决你采集乱码的问题。

阅读(1530) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~