向服务器请求压缩数据格式,并解压缩数据
#!/usr/bin/env python
# encoding=utf-8import urllib2, httplibdef writeFile(fname, data):f = open(fname, "w")f.write(data)f.close()if __name__ == '__main__':httplib.HTTPConnection.debuglevel = 1request = urllib2.Request('http://www.163.com/')request.add_header('Accept-encoding', 'gzip') # 向服务器请求压缩数据opener = urllib2.build_opener()f = opener.open(request)data = f.read() # 读取页面返回的数据f.close()print "压缩的数据长度为:%d" %len(data)writeFile("a.html", data)import StringIO, gzipcompressedstream = StringIO.StringIO(data)gziper = gzip.GzipFile(fileobj=compressedstream)data2 = gziper.read() # 读取解压缩后数据print "解压缩后数据长度为:%d" %len(data2)writeFile("aa.html", data2)
运行结果:
[zcm@python #25]$./del.py
压缩的数据长度为:100457
解压缩后数据长度为:358659
[zcm@python #26]$wc *.html4556 16010 358659 aa.html374 2197 100457 a.html4930 18207 459116 总用量
[zcm@python #27]$