范例1: gzip
import StringIO
import gzip compresseddata = gzip方式压缩的字符串(html)
compressedstream = StringIO.StringIO(compresseddata)
gzipper = gzip.GzipFile(fileobj=compressedstream)
data = gzipper.read() # data就是解压后的数据
一个简单的例子
import urllib2
from StringIO import StringIO
import gzip def loadData(url):
request = urllib2.Request(url)
request.add_header('Accept-encoding', 'gzip')
response = urllib2.urlopen(request)
if response.info().get('Content-Encoding') == 'gzip':
print 'gzip enabled'
buf = StringIO(response.read())
f = gzip.GzipFile(fileobj=buf)
data = f.read()
else:
data = response.read()
return data