2016-10-23 3 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' 

이 어떤 인코딩을

? 표준 라이브러리를 기반으로 디코드 할 수 있습니까?
이 문제에 대한 통찰력을 미리 주셔서 감사합니다!

추신 : 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의 사용을) 완벽하게 작동하고 대부분의 경우에 있어야합니다 선호. 그건, 제 3 자 라이브러리 (따라서 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...)' 
관련 문제