我想发出一个没有任何内容数据的HEAD请求,以节省带宽。我正在使用urllib.request
。但是,经过测试,似乎HEAD请求也获得了数据吗?这是怎么回事?
Python 3.4.2 (v3.4.2:ab2c023a9432, Oct 6 2014, 22:16:31) [MSC v.1600 64 bit (AM
D64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import urllib.request
>>> req = urllib.request.Request("http://www.google.com", method="HEAD")
>>> resp = urllib.request.urlopen(req)
>>> a = resp.read()
>>> len(a)
24088
该http://www.google.com
URL重定向:
$ curl -D - -X HEAD http://www.google.com
HTTP/1.1 302 Found
Cache-Control: private
Content-Type: text/html; charset=UTF-8
Location: http://www.google.co.uk/?gfe_rd=cr&ei=A8sXVZLOGvHH8ge1jYKwDQ
Content-Length: 261
Date: Sun, 29 Mar 2015 09:50:59 GMT
Server: GFE/2.0
Alternate-Protocol: 80:quic,p=0.5
并urllib.request
已按照重定向进行,向该新位置发出GET请求:
>>> import urllib.request
>>> req = urllib.request.Request("http://www.google.com", method="HEAD")
>>> resp = urllib.request.urlopen(req)
>>> resp.url
'http://www.google.co.uk/?gfe_rd=cr&ei=ucoXVdfaJOTH8gf-voKwBw'
您必须构建自己的处理程序堆栈以防止这种情况;HTTPRedirectHandler
发出HEAD
方法操作时,它不够聪明,无法处理重定向。改编自《如何防止Python的urllib(2)重定向到Python 3之后》中的Alan Duan的示例将为您提供:
import urllib.request
class NoRedirection(urllib.request.HTTPErrorProcessor):
def http_response(self, request, response):
return response
https_response = http_response
opener = urllib.request.build_opener(NoRedirection)
req = urllib.request.Request("http://www.google.com", method="HEAD")
resp = opener.open(req)
您最好使用该requests
库;它allow_redirects=False
在使用requests.head()
或requests.Session().head()
可调用对象时进行了显式设置,因此您可以在其中看到原始结果:
>>> import requests
>>> requests.head('http://www.google.com')
<Response [302]>
>>> _.headers['Location']
'http://www.google.co.uk/?gfe_rd=cr&ei=FcwXVbepMvHH8ge1jYKwDQ'
即使启用了重定向,该response.history
列表也使您可以访问中间请求,并且也requests
对重定向的调用使用正确的方法:
>>> response = requests.head('http://www.google.com', allow_redirects=True)
>>> response.url
'http://www.google.co.uk/?gfe_rd=cr&ei=8e0XVYfGMubH8gfJnoKoDQ'
>>> response.history
[<Response [302]>]
>>> response.history[0].url
'http://www.google.com/'
>>> response.request.method
'HEAD'
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句