Python: example of how to request and decompress data from the server.
This example describes how to request and decompress data from the server in Python. We will share this with you for your reference. The details are as follows:
Request to the server to compress the data format and decompress the data
#! /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 = 1 request = urllib2.Request ('HTTP: // www.163.com/') request. add_header ('Accept-encoding ', 'gzip') # request to the server to compress data opener = urllib2.build _ opener () f = opener. open (request) data = f. read () # read the data returned by the page f. close () print "Compressed data Length: % d" % len (data) writeFile ("a.html", data) import StringIO, gzip compressedstream = StringIO. stringIO (data) gziper = gzip. gzipFile (fileobj = compressedstream) data2 = gziper. read () # read and decompress data print "after decompression, the Data Length is % d" % len (data2) writeFile ("aa.html", data2)
Running result:
[Zcm @ python #25] $. /del. the Data Length compressed by py is 100457. After decompression, the Data Length is 358659 [zcm @ python #26] $ wc *. html 4556 16010 358659 aa.html 374 2197 100457 a.html 4930 18207 total usage [zcm @ python #27] $