2에서 HEAD HTTP 요청을 어떻게 보내나요?
내가 여기서 여기서 보낼 주어진 URL의 헤더를 가져 오기 위해 MIME 유형을 사용할 수 있습니다. http://somedomain/foo/
예를 들어 HTML 문서 또는 JPEG 이미지를 반환 하는지 확인하고 싶습니다 . 따라서 콘텐츠를 다운로드하지 않아도 MIME 형식을 읽을 수 있습니다. 누구나 쉬운 방법을 알고 있습니까?
편집 :이 답변은 효과가 요즘에는 한대로 요청 라이브러리를 사용합니다 .
httplib를 사용하십시오 .
>>> import httplib
>>> conn = httplib.HTTPConnection("www.google.com")
>>> conn.request("HEAD", "/index.html")
>>> res = conn.getresponse()
>>> print res.status, res.reason
200 OK
>>> print res.getheaders()
[('content-length', '0'), ('expires', '-1'), ('server', 'gws'), ('cache-control', 'private, max-age=0'), ('date', 'Sat, 20 Sep 2008 06:43:36 GMT'), ('content-type', 'text/html; charset=ISO-8859-1')]
getheader(name)
특정 헤더를 얻는 것도 있습니다 .
urllib2 를 사용하여 HEAD 요청을 수행 할 수 있습니다. urllib2는 URL을 호스트 이름과 경로로 분할하지 않고 URL을 구문 분석하기 때문에 httplib를 사용하는 것보다 약간 좋습니다.
>>> import urllib2
>>> class HeadRequest(urllib2.Request):
... def get_method(self):
... return "HEAD"
...
>>> response = urllib2.urlopen(HeadRequest("http://google.com/index.html"))
이전과 같이 response.info ()를 통해 헤더를 사용할 수 있습니다. 흥미롭게도 리디렉션 된 URL을 사용할 수 있습니다.
>>> print response.geturl()
http://www.google.com.au/index.html
의무적 인 방법 :Requests
import requests
resp = requests.head("http://www.google.com")
print resp.status_code, resp.text, resp.headers
요청 라이브러리도 필요한 조치를 취할 것 입니다.
다만 :
import urllib2
request = urllib2.Request('http://localhost:8080')
request.get_method = lambda : 'HEAD'
response = urllib2.urlopen(request)
response.info().gettype()
편집 : 방금 httplib2 : D가 있음을 깨달았습니다.
import httplib2
h = httplib2.Http()
resp = h.request("http://www.google.com", 'HEAD')
assert resp[0]['status'] == 200
assert resp[0]['content-type'] == 'text/html'
...
완성도를 높이기 위해 httplib를 사용하여 처리되는 답변과 동등한 Python3 답변을 얻습니다 .
가 라이브러리 더 이상 HTTPLIB가 아니라 http.client 라고 불리는 것은 기본적으로 동일한 코드입니다.
from http.client import HTTPConnection
conn = HTTPConnection('www.google.com')
conn.request('HEAD', '/index.html')
res = conn.getresponse()
print(res.status, res.reason)
import httplib
import urlparse
def unshorten_url(url):
parsed = urlparse.urlparse(url)
h = httplib.HTTPConnection(parsed.netloc)
h.request('HEAD', parsed.path)
response = h.getresponse()
if response.status/100 == 3 and response.getheader('Location'):
return response.getheader('Location')
else:
return url
제쳐두고, httplib를 사용할 때 (최소한 2.5.2에서) HEAD 요청의 응답을 읽으려고하면 (readline에서) 차단되고 실패합니다. 응답에서 읽기를 실행하지 않으면 연결에서 다른 요청을 보낼 수 없으므로 새 요청을 열어야합니다. 또는 요청 사이에 긴 지연을 허용하십시오.
httplib가 urllib2보다 약간 빠르다는 것을 발견했습니다. 하나는 httplib를 사용하고 다른 하나는 urllib2를 사용하는 두 프로그램의 시간을 측정하여 HEAD 요청을 10,000 개의 URL로 보냅니다. httplib는 몇 분 더 빨랐습니다. httplib 의 총 통계 : 실제 6m21.334s 사용자 0m2.124s sys 0m16.372s
그리고 urllib2 의 총 통계는 다음과 같습니다. 실제 9m1.380s 사용자 0m16.666s sys 0m28.565s
다른 사람이 이것에 대한 의견을 가지고 있습니까?
그리고 또 다른 접근 방식 (Pawel 답변과 유사) :
import urllib2
import types
request = urllib2.Request('http://localhost:8080')
request.get_method = types.MethodType(lambda self: 'HEAD', request, request.__class__)
인스턴스 수준에서 제한되지 않은 메서드를 사용하지 않기 위해.
아마도 더 쉬울 것입니다 : urllib 또는 urllib2를 사용하십시오.
>>> import urllib
>>> f = urllib.urlopen('http://google.com')
>>> f.info().gettype()
'text/html'
f.info ()는 사전과 같은 객체이므로 f.info () [ 'content-type'] 등을 할 수 있습니다.
http://docs.python.org/library/urllib.html
http://docs.python.org/library/urllib2.html
http://docs.python.org/library/httplib.html
문서에 따르면 httplib는 일반적으로 직접 사용되지 않습니다.
참고 URL : https://stackoverflow.com/questions/107405/how-do-you-send-a-head-http-request-in-python-2
'IT' 카테고리의 다른 글
PHP에서 데이터를 암호화 / 복호화하는 방법은 무엇입니까? (0) | 2020.08.04 |
---|---|
동일한 junit 테스트를 반복해서 말 수 있습니까? (0) | 2020.08.04 |
MySQL 쿼리-오늘과 지난 30 일 기록 레코드 (0) | 2020.08.04 |
bash에서 wc의 정수 만 가져옵니다. (0) | 2020.08.04 |
'패키지'요소가 신뢰할 수 없음 (0) | 2020.08.04 |