Python爬虫获取html页面乱码解决方案

用python做网页爬虫时经常会出现乱码问题。下面给出解决中文乱码问题的解决方法。

需要安装chardet模块

pip install chardet

安装是否成功  使用pip list命令查看, 如果有出现chardet说明安装OK

示例:

  爬取网易网页时,返回的html页面出现乱码,网易是GB2312编码, 解决如下:

import urllib2  
import sys  
import chardet  
  
req = urllib2.Request("http://www.163.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  

  

posted @ 2018-03-21 19:57  听障老男孩  阅读(524)  评论(0编辑  收藏  举报