Python:从 urllib2.urlopen 调用获取 HTTP 标头? [英] Python: Get HTTP headers from urllib2.urlopen call?

查看:80
本文介绍了Python:从 urllib2.urlopen 调用获取 HTTP 标头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当调用 urlopen 时,urllib2 会获取整个页面吗?

Does urllib2 fetch the whole page when a urlopen call is made?

我只想读取 HTTP 响应标头而不获取页面.看起来 urllib2 打开 HTTP 连接,然后随后获取实际的 HTML 页面……还是只是开始使用 urlopen 调用缓冲页面?

I'd like to just read the HTTP response header without getting the page. It looks like urllib2 opens the HTTP connection and then subsequently gets the actual HTML page... or does it just start buffering the page with the urlopen call?

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

推荐答案

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

Use the response.info() method to get the headers.

来自 urllib2 文档:

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

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

...

此函数返回一个类文件对象,并带有两个附加方法:

This function returns a file-like object with two additional methods:

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

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

So, for your example, try stepping through the result of response.info().headers for what you're looking for.

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

Note the major caveat to using httplib.HTTPMessage is documented in python issue 4773.

这篇关于Python:从 urllib2.urlopen 调用获取 HTTP 标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆