2016-10-23 38 views
0

當我打開這個網址我得到這樣的響應:解碼urllib.request裏響應

r = Request(r'http://airdates.tv/') 
h = urlopen(r).readline() 
print(h) 

響應:

b'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x00\xed\xbdkv\xdbH\x96.\xfa\xbbj\x14Q\xaeuJ\xce\xee4E\x82\xa4(9m\xe7\xd2\xd3VZ\xaf2e\xab2k\xf5\xc2\n' 

什麼編碼這是什麼? 有沒有基於標準庫來解碼它的方法?
預先感謝您對此事的任何見解!

PS:它似乎是gzip。

回答

4

它是gzip壓縮的HTML,正如你懷疑的那樣。

而不是使用urllib使用requests這將解壓縮與您的迴應:

import requests 

r = requests.get('http://airdates.tv/') 
print(r.text) 

你可以用pip install requests安裝它,永不回頭。


如果你真的必須限制自己的標準庫,然後用gzip模塊解壓:

import gzip 
import urllib2 
from cStringIO import StringIO 

f = urllib2.urlopen('http://airdates.tv/') 

# how to determine the content encoding 
content_encoding = f.headers.get('Content-Encoding') 
#print(content_encoding) 

# how to decompress gzip data with Python 3 
if content_encoding == 'gzip': 
    response = gzip.decompress(f.read()) 

# decompress with Python 2 
if content_encoding == 'gzip': 
    gz = gzip.GzipFile(fileobj=StringIO(f.read()) 
    response = gz.read() 
+0

我看到,請求不處理它不費吹灰之力。我仍然希望用一個標準庫來完成它。我認爲這個答案可能會導致我這樣的解決方案:http://stackoverflow.com/questions/6123223/howto-uncompress-gzipped-data-in-a-byte-array – jony

+0

瞭解它:'zlib.decompress(gz_data, 16 + zlib.MAX_WBITS)' – jony

+0

哦,我發佈了我正在使用的解決方案,但您的答案更完整!從頁面檢索內容編碼非常有用!謝謝。 – jony

0

mhawke的解決方案(使用requests代替urllib)完美的作品,並在大多數情況下應該是首選。這就是說,我正在尋找一個解決方案,不需要安裝第三方庫(因此我選擇urllib而不是requests)。

我發現使用標準庫的解決方案:

import zlib 
from urllib.request import Request, urlopen 

r = Request(r'http://airdates.tv/') 
h = urlopen(r).read() 
decomp_gzip = zlib.decompress(h, 16+zlib.MAX_WBITS) 
print(decomp_gzip) 

其產生以下響應:

b'<!DOCTYPE html>\n (continues...)'