這篇文章主要介紹python如何實現gzip/deflate支持,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
成都創新互聯公司從2013年創立,先為徽州等服務建站,徽州等地企業,進行企業商務咨詢服務。為徽州企業網站制作PC+手機+微官網三網同步一站式服務解決您的所有建站問題。
gzip/deflate支持
現在的網頁普遍支持gzip壓縮,這往往可以解決大量傳輸時間,以VeryCD的主頁為例,未壓縮版本247K,壓縮了以后45K,為原來的1/5。這就意味著抓取速度會快5倍。
然而python的urllib/urllib2默認都不支持壓縮,要返回壓縮格式,必須在request的header里面寫明’accept-encoding’,然后讀取response后更要檢查header查看是否有’content-encoding’一項來判斷是否需要解碼,很繁瑣瑣碎。如何讓urllib2自動支持gzip, defalte呢?
其實可以繼承BaseHanlder類,然后build_opener的方式來處理:
import urllib2 from gzip import GzipFile from StringIO import StringIO class ContentEncodingProcessor(urllib2.BaseHandler): """A handler to add gzip capabilities to urllib2 requests """ # add headers to requests def http_request(self, req): req.add_header("Accept-Encoding", "gzip, deflate") return req # decode def http_response(self, req, resp): old_resp = resp # gzip if resp.headers.get("content-encoding") == "gzip": gz = GzipFile( fileobj=StringIO(resp.read()), mode="r" ) resp = urllib2.addinfourl(gz, old_resp.headers, old_resp.url, old_resp.code) resp.msg = old_resp.msg # deflate if resp.headers.get("content-encoding") == "deflate": gz = StringIO( deflate(resp.read()) ) resp = urllib2.addinfourl(gz, old_resp.headers, old_resp.url, old_resp.code) # 'class to add info() and resp.msg = old_resp.msg return resp # deflate support import zlib def deflate(data): # zlib only provides the zlib compress format, not the deflate format; try: # so on top of all there's this workaround: return zlib.decompress(data, -zlib.MAX_WBITS) except zlib.error: return zlib.decompress(data) 然后就簡單了, encoding_support = ContentEncodingProcessor opener = urllib2.build_opener( encoding_support, urllib2.HTTPHandler ) #直接用opener打開網頁,如果服務器支持gzip/defalte則自動解壓縮 content = opener.open(url).read()
以上是“python如何實現gzip/deflate支持”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注創新互聯行業資訊頻道!
文章名稱:python如何實現gzip/deflate支持
鏈接地址:http://m.newbst.com/article6/isjdig.html
成都網站建設公司_創新互聯,為您提供關鍵詞優化、移動網站建設、網站設計、營銷型網站建設、商城網站、電子商務
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯