Python爬蟲的亂碼問題?
問題描述
使用python實現模擬登陸并爬取返回頁面的時候出現了亂碼,目標網頁的編碼使用utf-8
相關代碼:
#coding=utf-8import urllibimport urllib2headers={ ’Accept’:’text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8’, ’Accept-Encoding’:’gzip, deflate’, ’Accept-Language’:’zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3’, ’Connection’:’keep-alive’, ’User-Agent’:’Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36’}payload={ ’_eventId’:’submit’, ’lt’:’_cF2A0EB3F-D044-046C-6F4A-C828DE0ACE8E_k8B4BE5F5-4CAD-375D-0DDC-FB84A18445DF’, ’password’:’’, ’submit’:’登 錄’, ’username’:’’}payload=urllib.urlencode(payload)request = urllib2.Request(posturl, payload, headers)print requestresponse = urllib2.urlopen(request)text = response.read()print text
控制臺輸出信息:
第一次遇見這種亂碼比較懵逼
問題解答
回答1:urllib2沒有處理壓縮的問題,你要使用gzip解壓,比如這樣
from StringIO import StringIOimport gzipif response.info().get(’Content-Encoding’) == ’gzip’: buf = StringIO(text) f = gzip.GzipFile(fileobj=buf) data = f.read()
總結urllib2比較底層,建議使用requests
相關文章:
1. node.js - 在vuejs-templates/webpack中dev-server.js里為什么要exports readyPromise?2. javascript - history.replaceState()無法改變query參數3. html5 - 如何實現圖中的刻度漸變效果?4. CSS3 border凹陷該如何編寫?5. css - 怎么實現一個圓點在一個范圍內亂飛6. css3 - transition屬性當鼠標一開的時候設置的時間不起作用7. 前端 - html5 audio不能播放8. css - 關于偽類背景問題9. html - 移動端radio無法選中10. javascript - 關于禁用文本選擇與復制的問題
