關于爬蟲亂碼有很多各式各樣的問題,這里不僅是中文亂碼,編碼轉換、還包括一些如日文、韓文 、俄文、藏文之類的亂碼處理,因為解決方式是一致的,故在此統一說明。
網絡爬蟲出現亂碼的原因
源網頁編碼和爬取下來后的編碼格式不一致。
如源網頁為gbk編碼的字節流,而我們抓取下后程序直接使用utf-8進行編碼并輸出到存儲文件中,這必然會引起亂碼 即當源網頁編碼和抓取下來后程序直接使用處理編碼一致時,則不會出現亂碼; 此時再進行統一的字符編碼也就不會出現亂碼了
注意區分
亂碼的解決方法
確定源網頁的編碼A,編碼A往往在網頁中的三個位置
1.http header的Content-Type
獲取服務器 header 的站點可以通過它來告知瀏覽器一些頁面內容的相關信息。 Content-Type 這一條目的寫法就是 "text/html; charset=utf-8"。
2.meta charset
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
3.網頁頭中Document定義
<script type="text/javascript"> if(document.charset){ alert(document.charset+"!!!!"); document.charset = 'GBK'; alert(document.charset); } else if(document.characterSet){ alert(document.characterSet+"????"); document.characterSet = 'GBK'; alert(document.characterSet); }
在獲取源網頁編碼時,依次判斷下這三部分數據即可,從前往后,優先級亦是如此。
以上三者中均沒有編碼信息 一般采用chardet等第三方網頁編碼智能識別工具來做
安裝: pip install chardet
官方網站: http://chardet.readthedocs.io/en/latest/usage.html
Python chardet 字符編碼判斷
使用 chardet 可以很方便的實現字符串/文件的編碼檢測 雖然HTML頁面有charset標簽,但是有些時候是不對的。那么chardet就能幫我們大忙了。
chardet實例
import urllib rawdata = urllib.urlopen('//www.jb51.net/').read() import chardet chardet.detect(rawdata) {'confidence': 0.99, 'encoding': 'GB2312'}
chardet可以直接用detect函數來檢測所給字符的編碼。函數返回值為字典,有2個元素,一個是檢測的可信度,另外一個就是檢測到的編碼。
在開發自用爬蟲過程中如何處理漢字編碼?
下面所說的都是針對python2.7,如果不加處理,采集到的都是亂碼,解決的方法是將html處理成統一的utf-8編碼 遇到windows-1252編碼,屬于chardet編碼識別訓練未完成
import chardet a='abc' type(a) str chardet.detect(a) {'confidence': 1.0, 'encoding': 'ascii'} a ="我" chardet.detect(a) {'confidence': 0.73, 'encoding': 'windows-1252'} a.decode('windows-1252') u'/xe6/u02c6/u2018' chardet.detect(a.decode('windows-1252').encode('utf-8')) type(a.decode('windows-1252')) unicode type(a.decode('windows-1252').encode('utf-8')) str chardet.detect(a.decode('windows-1252').encode('utf-8')) {'confidence': 0.87625, 'encoding': 'utf-8'} a ="我是中國人" type(a) str {'confidence': 0.9690625, 'encoding': 'utf-8'} chardet.detect(a) # -*- coding:utf-8 -*- import chardet import urllib2 #抓取網頁html html = urllib2.urlopen('//www.jb51.net/').read() print html mychar=chardet.detect(html) print mychar bianma=mychar['encoding'] if bianma == 'utf-8' or bianma == 'UTF-8': html=html.decode('utf-8','ignore').encode('utf-8') else: html =html.decode('gb2312','ignore').encode('utf-8') print html print chardet.detect(html)
新聞熱點
疑難解答