python中的head,如何在Python 2中发送HEAD HTTP请求?

如何在Python 2中发送HEAD HTTP请求?

我在这里尝试做的是获取给定URL的标题,以便我可以确定MIME类型。 我希望能够看到http://somedomain/foo/是否会返回HTML文档或JPEG图像。 因此,我需要弄清楚如何发送HEAD请求,以便我可以读取MIME类型而无需下载内容。 有谁知道这样做的简单方法?

11个解决方案

105 votes

urllib2可用于执行HEAD请求。 这比使用httplib好一点,因为urllib2为您解析URL而不是要求您将URL拆分为主机名和路径。

>>> 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

doshea answered 2019-07-07T22:19:08Z

102 votes

编辑:这个答案有效,但现在您应该使用请求库,如下面的其他答案所述。

使用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)来获取特定的标题。

Eevee answered 2019-07-07T22:18:36Z

58 votes

必要的Requests方式:

import requests

resp = requests.head("http://www.google.com")

print resp.status_code, resp.text, resp.headers

K Z answered 2019-07-07T22:19:32Z

36 votes

我相信也应该提到Requests库。

daliusd answered 2019-07-07T22:19:57Z

16 votes

只是:

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'

...

链接文字

Paweł Prażak answered 2019-07-07T22:20:26Z

7 votes

为了完整性,使用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)

Octavian Damiean answered 2019-07-07T22:20:57Z

2 votes

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

Pranay Agarwal answered 2019-07-07T22:21:15Z

1 votes

顺便说一下,当使用httplib时(至少在2.5.2上),尝试读取HEAD请求的响应将阻塞(在readline上)并随后失败。 如果您没有对响应发出读取,则无法在连接上发送另一个请求,您将需要打开一个新请求。 或者在请求之间接受长时间延迟。

answered 2019-07-07T22:21:41Z

1 votes

我发现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

有没有人对此有所了解?

IgorGanapolsky answered 2019-07-07T22:22:21Z

0 votes

还有另一种方法(类似于Pawel的回答):

import urllib2

import types

request = urllib2.Request('http://localhost:8080')

request.get_method = types.MethodType(lambda self: 'HEAD', request, request.__class__)

只是为了避免在实例级别有无限制的方法。

estani answered 2019-07-07T22:22:53Z

-4 votes

可能更容易:使用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通常不直接使用。

answered 2019-07-07T22:23:53Z

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值