在開發自用爬蟲時,最惱人的莫過於編碼不統一:有的網頁是 utf-8,有的是 gb2312,還有的是 gbk。若不特別處理,抓回來的全是亂碼。解法是把 HTML 一律轉成 utf-8。
以下程式碼針對 Python 2.7,需先下載安裝 chardet:
#coding:utf-8
#chardet 需要下載安裝
import chardet
#抓取網頁html
line = "https://www.linuxidc.com"
html_1 = urllib2.urlopen(line,timeout=120).read()
#print html_1
encoding_dict = chardet.detect(html_1)
#print encoding
web_encoding = encoding_dict['encoding']
if web_encoding == 'utf-8' or web_encoding == 'UTF-8':
html = html_1
else :
html = html_1.decode('gbk','ignore').encode('utf-8')
#有以上處理,整個html就不會是亂碼。
關鍵在於 chardet.detect():它會回傳一個字典,其中的 encoding 鍵就是偵測到的編碼。若已是 utf-8 就直接使用,否則先 decode 成目標字集再用 'ignore' 忽略無法解碼的位元組,最後 encode 回 utf-8。實務上要留意:chardet 並非百分之百準確,遇到判定失準的頁面時,可考慮尊重 HTTP 回應標頭或 meta 標籤宣告的編碼作為優先依據。
Python解析xml文檔實例 https://www.linuxidc.com/Linux/2012-02/54760.htm
《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] https://www.linuxidc.com/Linux/2013-06/85425.htm
《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] https://www.linuxidc.com/Linux/2013-11/92693.htm
Python腳本獲取Linux系統信息 https://www.linuxidc.com/Linux/2013-08/88531.htm
在Ubuntu下用Python搭建桌面算法交易研究環境 https://www.linuxidc.com/Linux/2013-11/92534.htm
Python 語言的發展簡史 https://www.linuxidc.com/Linux/2014-09/107206.htm
Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡