python處理抓取中文編碼和判斷編碼

pythontab發表於2014-02-27

在開發自用爬蟲過程中,有的網頁是utf-8,有的是gb2312,有的是gbk,如果不加處理,採集到的都是亂碼,解決的方法是將html處理成統一的utf-8編碼

版本python2.7

#coding:utf-8
import chardet
#抓取網頁html
line = "http://www.pythontab.com"
html_1 = urllib2.urlopen(line,timeout=120).read()
encoding_dict = chardet.detect(html_1)
print encoding
web_encoding = encoding_dict['encoding']
#處理,整個html就不會是亂碼。
if web_encoding == 'utf-8' or web_encoding == 'UTF-8':
html = html_1
else :
html = html_1.decode('gbk','ignore').encode('utf-8')


相關文章