本文實例講述了Python實現(xiàn)向服務(wù)器請求壓縮數(shù)據(jù)及解壓縮數(shù)據(jù)的方法。分享給大家供大家參考,具體如下:
向服務(wù)器請求壓縮數(shù)據(jù)格式,并解壓縮數(shù)據(jù)
#!/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') # 向服務(wù)器請求壓縮數(shù)據(jù) opener = urllib2.build_opener() f = opener.open(request) data = f.read() # 讀取頁面返回的數(shù)據(jù) f.close() print "壓縮的數(shù)據(jù)長度為:%d" %len(data) writeFile("a.html", data) import StringIO, gzip compressedstream = StringIO.StringIO(data) gziper = gzip.GzipFile(fileobj=compressedstream) data2 = gziper.read() # 讀取解壓縮后數(shù)據(jù) print "解壓縮后數(shù)據(jù)長度為:%d" %len(data2) writeFile("aa.html", data2)運(yùn)行結(jié)果:
[zcm@python #25]$./del.py壓縮的數(shù)據(jù)長度為:100457解壓縮后數(shù)據(jù)長度為:358659[zcm@python #26]$wc *.html 4556 16010 358659 aa.html 374 2197 100457 a.html 4930 18207 459116 總用量[zcm@python #27]$
希望本文所述對大家Python程序設(shè)計有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選