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
相關文章:
