Example of Python implementation for requesting and extracting compressed data from the server

  • 2020-06-03 07:06:36
  • OfStack

An example of Python shows how to request compressed data from the server and extract the compressed data. To share for your reference, specific as follows:

Request the compressed data format from the server and extract the data


#!/usr/bin/env python
# encoding=utf-8
import urllib2, httplib
def 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 compressed data from the server 
  opener = urllib2.build_opener()
  f = opener.open(request)
  data = f.read()     #  Read the data returned by the page 
  f.close()
  print " The compressed data length is: %d" %len(data)
  writeFile("a.html", data)
  import StringIO, gzip
  compressedstream = StringIO.StringIO(data)
  gziper = gzip.GzipFile(fileobj=compressedstream)
  data2 = gziper.read()  #  Read the decompressed data 
  print " The length of uncompressed data is: %d" %len(data2)
  writeFile("aa.html", data2)

Operation results:


[zcm@python #25]$./del.py
 The compressed data length is: 100457
 The length of uncompressed data is: 358659
[zcm@python #26]$wc *.html
 4556 16010 358659 aa.html
  374  2197 100457 a.html
 4930 18207 459116  The total amount 
[zcm@python #27]$

More about Python related topics: interested readers to view this site "Python file and directory skills summary", "Python skills summary text file", "Python URL skills summary", "Python pictures skills summary", "Python data structure and algorithm tutorial", "Python Socket programming skills summary", "Python function using skills summary", "Python string skills summary" and "Python introductory and advanced tutorial"

I hope this article has been helpful in Python programming.


Related articles: