2016-10-23 47 views
0

urllib.request:デコード私はこのURLを開くと、私はこの応答を取得しています応答

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モジュールとそれを解凍し、標準ライブラリに自分自身を制限する必要がある場合:(代わりにurllibrequestsを使用して)

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のソリューションは、完全に、ほとんどの場合で動作する必要があります好ましい。 しかし、サードパーティ製のライブラリをインストールする必要がないソリューションを探していました(したがって、urllibrequestsより選択しました)。以下の応答が得られ

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...)' 
関連する問題