且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2021-10-22 23:16:51

edit:这个答案有效,但现在你应该只使用 requests 库,如下面的其他答案所述.

edit: This answer works, but nowadays you should just use the requests library as mentioned by other answers below.

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

There's also a getheader(name) to get a specific header.