python如何读取配置文件获取url以及hhead_urllib-Python:是否从urllib2.urlopen调用获取HTTP标头?...

实际上,似乎urllib2可以执行HTTP HEAD请求。

上面@reto链接到的问题说明了如何获取urllib2来执行HEAD请求。

这是我的看法:

import urllib2

# Derive from Request class and override get_method to allow a HEAD request.

class HeadRequest(urllib2.Request):

def get_method(self):

return "HEAD"

myurl = 'http://bit.ly/doFeT'

request = HeadRequest(myurl)

try:

response = urllib2.urlopen(request)

response_headers = response.info()

# This will just display all the dictionary key-value pairs. Replace this

# line with something useful.

response_headers.dict

except urllib2.HTTPError, e:

# Prints the HTTP Status code of the response but only if there was a

# problem.

print ("Error code: %s" % e.code)

如果使用Wireshark网络协议分析器等进行检查,则可以看到它实际上是在发送HEAD请求而不是GET。

这是上面代码的HTTP请求和响应,如Wireshark所捕获:

HEAD / doFeT HTTP / 1.1

接受编码:身份

主办: 一点点地

连接方式:关闭

用户代理:Python-urllib / 2.7

HTTP / 1.1 301已移动

服务器:nginx

日期:2012年2月19日,星期日 格林尼治标准时间13:20:56

内容类型:text / html; 字符集= utf-8

缓存控制:私有; 最大年龄= 90

位置: [http://www.kidsidebyside.org/?p=445]

MIME版本:1.0

内容长度:127

连接方式:关闭

Set-Cookie: _bit = 4f40f738-00153-02ed0-421cf10a; domain = .bit.ly; expires = Fri Aug 17 13:20:56 2012; path = /; HttpOnly

但是,如另一个问题中的一个注释中所述,如果所讨论的URL包含重定向,则urllib2将向目标而不是HEAD发送GET请求。 如果您确实只想发出HEAD请求,则这可能是一个主要缺点。

上面的请求涉及重定向。 这是到目的地的请求,由Wireshark捕获:

GET / 2009/05 /与我们/HTTP/1.1一起画圆的统一

接受编码:身份

主持人:www.kidsidebyside.org

连接方式:关闭

用户代理:Python-urllib / 2.7

使用urllib2的替代方法是使用Joe Gregorio的httplib2库:

import httplib2

url = "http://bit.ly/doFeT"

http_interface = httplib2.Http()

try:

response, content = http_interface.request(url, method="HEAD")

print ("Response status: %d - %s" % (response.status, response.reason))

# This will just display all the dictionary key-value pairs. Replace this

# line with something useful.

response.__dict__

except httplib2.ServerNotFoundError, e:

print (e.message)

这具有将HEAD请求用于初始HTTP请求和重定向到目标URL的优点。

这是第一个请求:

HEAD / doFeT HTTP / 1.1

主持人:bit.ly

接受编码:gzip, 放气

用户代理:Python-httplib2 / 0.7.2(gzip)

这是到目的地的第二个请求:

HEAD / 2009/05 /与我们/HTTP/1.1绘制圆的统一体

主持人:www.kidsidebyside.org

接受编码:gzip,放气

用户代理:Python-httplib2 / 0.7.2(gzip)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值