Python:从urllib2.urlopen调用获取HTTP头?

shi*_*eta 47 python forwarding urllib

是否urllib2urlopen拨打电话时获取整个页面?

我想在不获取页面的情况下读取HTTP响应头.它看起来像urllib2打开HTTP连接,然后获取实际的HTML页面......或者它是否只是通过urlopen调用开始缓冲页面?

import urllib2
myurl = 'http://www.kidsidebyside.org/2009/05/come-and-draw-the-circle-of-unity-with-us/'
page = urllib2.urlopen(myurl) // open connection, get headers

html = page.readlines()  // stream page
Run Code Online (Sandbox Code Playgroud)

小智 49

使用该response.info()方法获取标头.

来自urllib2文档:

urllib2.urlopen(url [,data] [,timeout])

...

此函数返回一个类似文件的对象,其中包含两个方法:

  • geturl() - 返回检索到的资源的URL,通常用于确定是否遵循重定向
  • info() - 以httplib.HTTPMessage实例的形式返回页面的元信息,例如标题(请参阅HTTP标头的快速参考)

因此,对于您的示例,请尝试逐步response.info().headers查看您要查找的内容.

请注意,在python issue 4773中记录了使用httplib.HTTPMessage的主要警告.

  • ***Python 3注意***首先,没有像`response.info().headers`,做一个`dict(response.info())`.其次,对于HTTP状态代码执行`response.status`. (20认同)
  • `headers`记录在哪里?还要考虑使用`response.info().items()`来返回键值dict. (3认同)
  • _**Python 2注意**_这就是你想要的:`response.info().getheader('Content-Type')`source:http://stackoverflow.com/questions/1653591/python-urllib2-response -header (2认同)

ret*_*eto 40

如何发送HEAD请求而不是普通的GET请求.以下剪辑(从类似的问题复制)就是这样做的.

>>> 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')]
Run Code Online (Sandbox Code Playgroud)

  • 我想会那样做! (2认同)

Sim*_*wsi 20

实际上,似乎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)
Run Code Online (Sandbox Code Playgroud)

如果您使用Wireshark网络协议analazer进行检查,您可以看到它实际上是发送了HEAD请求,而不是GET.

这是来自上面代码的HTTP请求和响应,由Wireshark捕获:

HEAD/doFeT HTTP/1.1
Accept-Encoding:identity
主机:bit.ly
连接:close
User-Agent:Python-urllib/2.7

HTTP/1.1 301移动
服务器:nginx
日期:太阳,2012年2月19日13:20:56 GMT
内容类型:text/html; charset = utf-8
缓存控制:私有; max-age = 90
位置: http://www.kidsidebyside.org/?p = 450
MIME-Version:1.0
Content-Length:127
连接:close
Set-Cookie:_bit = 4f40f738-00153-02ed0-421cf10a; domain = .bit.ly; expires = Fri Aug 17 13:20:56 2012; path = /; 仅Http

但是,如其他问题中的一条评论中所述,如果相关URL包含重定向,则urllib2将向目标执行GET请求,而不是HEAD.如果你真的只想提出HEAD请求,这可能是一个主要的缺点.

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

GET/2009/05/come-and-draw-the-unity-of-unity-with-us/HTTP/1.1
Accept-Encoding:identity
Host:www.kidsidebyside.org
Connection:close
User-Agent: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)
Run Code Online (Sandbox Code Playgroud)

这具有对初始HTTP请求和到目标URL的重定向请求使用HEAD请求的优点.

这是第一个请求:

HEAD/doFeT HTTP/1.1
主机:bit.ly
accept-encoding:gzip,deflate
user-agent:Python-httplib2/0.7.2(gzip)

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

HEAD/2009/05/come-and-draw-the-unity-of-unity-with-us/HTTP/1.1
主机:www.kidsidebyside.org
accept-encoding:gzip,deflate
user-agent:Python-httplib2/0.7 .2(gzip)


Ale*_*lli 8

urllib2.urlopen执行HTTP GET(或POST,如果你提供数据参数),而不是HTTP HEAD(如果它执行后者,你当然不能对页面主体进行读取或其他访问).


qua*_*nta 5

一内胆:

$ python -c "import urllib2; print urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1)).open(urllib2.Request('http://google.com'))"
Run Code Online (Sandbox Code Playgroud)