在开发自用爬虫过程中,有的网页是utf-8,有的是gb2312,有的是gbk,怎么办?
下面所说的都是针对python2.7
如果不加处理,采集到的都是乱码,解决的方法是将html处理成统一的utf-8编码。
#chardet 需要下载安装
import chardet
#抓取网页html
html_1 = urllib2.urlopen(line,timeout=120).read()
#print html_1
mychar=chardet.detect(html_1)
#print mychar
bianma=mychar['encoding']
if bianma == 'utf-8' or bianma == 'UTF-8':
  #html=html.decode('utf-8','ignore').encode('utf-8')
 html=html_1
else :
  html =html_1.decode('gb2312','ignore').encode('utf-8')
有以上处理,整个html就不会是乱码。