2013-04-18 2 views
1

httplib/http.client를 사용하여 들어오는 응답의 인코딩을 얻으려면 어떻게해야합니까?httplib/http.client를 사용하여 응답 인코딩 가져 오기

getheaders()를 사용하여 Content-Type의 일부로 볼 수 있지만, 몇 가지 다른 형식이 될 수 있으므로 구문 분석이 나쁜 습관이라고 생각합니다. 그리고 httplib에서 특정 메서드를 사용해야합니다. /http.client 대신 :

>>> r = h.getresponse() 
>>> r.getheaders() 
[('transfer-encoding', 'chunked'), ('expires', 'Tue, 11 Oct 1988 22:00:00 GMT'), ('vary', 'Accept-Encoding'), ('server', 'nginx/1.2.6'), ('connection', 'keep-alive'), ('pragma', 'no-cache'), ('cache-control', 'no-cache, must-revalidate'), ('date', 'Thu, 18 Apr 2013 00:46:18 GMT'), ('content-type', 'text/html; charset=utf-8')] 

들어오는 인코딩을 얻는 가장 좋은 방법은 무엇입니까?

답변

0

직접적인 대답은 아니지만 아마도 유용 할 것입니다. requests 라이브러리를 사용하십시오.

사람들이 자신의 http 라이브러리를 만드는 것을 중단 한 이유가 있습니다. 사실, httplib은 http 라이브러리를 사용하는 urllib을 사용한다고합니다. 교대로 요청은 urllib3을 사용합니다.

>>> import requests 
>>> r = requests.get("http://bitbucket.org") 
dir>>> dir(r) 
['__bool__', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__nonzero__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_content', '_content_consumed', 'apparent_encoding', 'close', 'connection', 'content', 'cookies', 'encoding', 'headers', 'history', 'iter_content', 'iter_lines', 'json', 'links', 'ok', 'raise_for_status', 'raw', 'reason', 'request', 'status_code', 'text', 'url'] 
>>> r.encoding 
'utf-8'