網頁資料壓縮(python deflate gzip),解壓縮
阿新 • • 發佈:2019-01-06
在寫爬蟲抓取網頁時,通過下面程式碼可以將網頁程式碼抓取回來,一般直接就是HTML的相關網頁程式碼。
data = urllib2.urlopen(url).read()
但有時,返回的是一些看不懂的資料。
這是通過Fiddler抓取回來的資料,其實在上面這個截圖中就可以看到,這個資料是被encoded過的,點選Response body is encoded.Click to decode.即可解密:
deocde後,就可以看到HTML程式碼:
其實,這些資料是被壓縮過的,而網頁壓縮一般有2種方式:
deflate 和 gzip,但實際上deflate已經比較過時了。
在通過爬蟲抓取後,需要對資料進行解壓縮,才能看到相應的網頁程式碼,這時,可以通過下面的python程式碼進行解壓縮:
import urllib2 from gzip import GzipFile from StringIO import StringIO import zlib def loadData(url): request = urllib2.Request(url) request.add_header('Accept-encoding', 'gzip,deflate') response = urllib2.urlopen(request) content = response.read() encoding = response.info().get('Content-Encoding') if encoding == 'gzip': content = gzip(content) elif encoding == 'deflate': content = deflate(content) return content def gzip(data): buf = StringIO(data) f = gzip.GzipFile(fileobj=buf) return f.read() def deflate(data): try: return zlib.decompress(data, -zlib.MAX_WBITS) except zlib.error: return zlib.decompress(data) def main(): url = "http://www.xxx.com/" content = loadData(url) print content if __name__ == '__main__': main()