我们经常通过python做采集网页数据的时候,会碰到一些乱码问题,今天给大家分享一个解决网页乱码,尤其是中文网页的通用方法。
首页我们需要安装chardet模块,这个可以通过easy_install 或者pip来安装。
安装完以后我们在控制台上导入模块,如果正常就可以。
比如我们遇到的一些ISO-8859-2也是可以通过下面的方法解决的。
直接上代码吧:
import
urllib2
import sys
import chardet
req = urllib2 . Request( "http://www.163.com/") ##这里可以换成http://www.baidu.com,http://www.sohu.com
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
import sys
import chardet
req = urllib2 . Request( "http://www.163.com/") ##这里可以换成http://www.baidu.com,http://www.sohu.com
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
通过上面的代码,相信能够解决你采集乱码的问题。