溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

python如何實現gzip/deflate支持

發布時間:2022-03-14 14:58:26 來源:億速云 閱讀:642 作者:小新 欄目:編程語言

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

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支持”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女