网页数据压缩(python deflate gzip),解压缩

在写爬虫抓取网页时,通过下面代码可以将网页代码抓取回来,一般直接就是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()

猜你喜欢

转载自blog.csdn.net/a33445621/article/details/80382446
今日推荐