python如何實(shí)現(xiàn)gzip/deflate支持

這篇文章主要介紹python如何實(shí)現(xiàn)gzip/deflate支持,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!

成都創(chuàng)新互聯(lián)公司從2013年創(chuàng)立,先為徽州等服務(wù)建站,徽州等地企業(yè),進(jìn)行企業(yè)商務(wù)咨詢服務(wù)。為徽州企業(yè)網(wǎng)站制作PC+手機(jī)+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問題。

gzip/deflate支持

現(xiàn)在的網(wǎng)頁普遍支持gzip壓縮,這往往可以解決大量傳輸時(shí)間,以VeryCD的主頁為例,未壓縮版本247K,壓縮了以后45K,為原來的1/5。這就意味著抓取速度會(huì)快5倍。

然而python的urllib/urllib2默認(rèn)都不支持壓縮,要返回壓縮格式,必須在request的header里面寫明’accept-encoding’,然后讀取response后更要檢查header查看是否有’content-encoding’一項(xiàng)來判斷是否需要解碼,很繁瑣瑣碎。如何讓urllib2自動(dòng)支持gzip, defalte呢?

其實(shí)可以繼承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打開網(wǎng)頁,如果服務(wù)器支持gzip/defalte則自動(dòng)解壓縮
content = opener.open(url).read()

以上是“python如何實(shí)現(xiàn)gzip/deflate支持”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!

文章名稱:python如何實(shí)現(xiàn)gzip/deflate支持
鏈接地址:http://muchs.cn/article6/isjdig.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供關(guān)鍵詞優(yōu)化、移動(dòng)網(wǎng)站建設(shè)、網(wǎng)站設(shè)計(jì)、營銷型網(wǎng)站建設(shè)、商城網(wǎng)站、電子商務(wù)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

h5響應(yīng)式網(wǎng)站建設(shè)