Python實現(xiàn)向服務器請求壓縮數(shù)據(jù)及解壓縮數(shù)據(jù)的方法示例
本文實例講述了Python實現(xiàn)向服務器請求壓縮數(shù)據(jù)及解壓縮數(shù)據(jù)的方法。分享給大家供大家參考,具體如下:
向服務器請求壓縮數(shù)據(jù)格式,并解壓縮數(shù)據(jù)
#!/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') # 向服務器請求壓縮數(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)
運行結果:
[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相關內(nèi)容感興趣的讀者可查看本站專題:《Python文件與目錄操作技巧匯總》、《Python文本文件操作技巧匯總》、《Python URL操作技巧總結》、《Python圖片操作技巧總結》、《Python數(shù)據(jù)結構與算法教程》、《Python Socket編程技巧總結》、《Python函數(shù)使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經(jīng)典教程》
希望本文所述對大家Python程序設計有所幫助。
相關文章
python實現(xiàn)幾種歸一化方法(Normalization Method)
這篇文章主要介紹了python實現(xiàn)幾種歸一化方法(Normalization Method),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-07-07Python中多線程thread與threading的實現(xiàn)方法
這篇文章主要介紹了Python中多線程thread與threading的實現(xiàn)方法,很重要的應用,需要的朋友可以參考下2014-08-08