關(guān)于爬蟲亂碼有很多各式各樣的問題,這里不僅是中文亂碼,編碼轉(zhuǎn)換、還包括一些如日文、韓文 、俄文、藏文之類的亂碼處理,因?yàn)榻鉀Q方式是一致的,故在此統(tǒng)一說明。
網(wǎng)絡(luò)爬蟲出現(xiàn)亂碼的原因
源網(wǎng)頁編碼和爬取下來后的編碼格式不一致。
如源網(wǎng)頁為gbk編碼的字節(jié)流,而我們抓取下后程序直接使用utf-8進(jìn)行編碼并輸出到存儲文件中,這必然會引起亂碼 即當(dāng)源網(wǎng)頁編碼和抓取下來后程序直接使用處理編碼一致時(shí),則不會出現(xiàn)亂碼; 此時(shí)再進(jìn)行統(tǒng)一的字符編碼也就不會出現(xiàn)亂碼了
注意區(qū)分
亂碼的解決方法
確定源網(wǎng)頁的編碼A,編碼A往往在網(wǎng)頁中的三個(gè)位置
1.http header的Content-Type
獲取服務(wù)器 header 的站點(diǎn)可以通過它來告知瀏覽器一些頁面內(nèi)容的相關(guān)信息。 Content-Type 這一條目的寫法就是 "text/html; charset=utf-8"。
2.meta charset
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
3.網(wǎng)頁頭中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); }
在獲取源網(wǎng)頁編碼時(shí),依次判斷下這三部分?jǐn)?shù)據(jù)即可,從前往后,優(yōu)先級亦是如此。
以上三者中均沒有編碼信息 一般采用chardet等第三方網(wǎng)頁編碼智能識別工具來做
安裝: pip install chardet
官方網(wǎng)站: http://chardet.readthedocs.io/en/latest/usage.html
Python chardet 字符編碼判斷
使用 chardet 可以很方便的實(shí)現(xiàn)字符串/文件的編碼檢測 雖然HTML頁面有charset標(biāo)簽,但是有些時(shí)候是不對的。那么chardet就能幫我們大忙了。
chardet實(shí)例
import urllib rawdata = urllib.urlopen('//www.jb51.net/').read() import chardet chardet.detect(rawdata) {'confidence': 0.99, 'encoding': 'GB2312'}
chardet可以直接用detect函數(shù)來檢測所給字符的編碼。函數(shù)返回值為字典,有2個(gè)元素,一個(gè)是檢測的可信度,另外一個(gè)就是檢測到的編碼。
在開發(fā)自用爬蟲過程中如何處理漢字編碼?
下面所說的都是針對python2.7,如果不加處理,采集到的都是亂碼,解決的方法是將html處理成統(tǒng)一的utf-8編碼 遇到windows-1252編碼,屬于chardet編碼識別訓(xùn)練未完成
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 #抓取網(wǎng)頁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)
新聞熱點(diǎn)
疑難解答
圖片精選