【问题标题】:Retrieve HTTPResponse even in case of error即使发生错误也能检索 HTTPResponse
【发布时间】:2012-06-06 14:17:01
【问题描述】:

在 Python 中(使用 Python 3.2,但我想它在 Python 2.x 中应该基本相同),我尝试向某个 URL 发出请求。

在出现Access Denied等错误的情况下,我得到一个异常:

>>> request = urllib.request.urlopen(myurl)
...
  File "/usr/lib/python3.2/urllib/request.py", line 495, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 401: Unauthorized

但即使出现错误,我也想查看请求的标头。

>>> request = urllib.request.urlopen(myurl)
>>> print(request.status)
401
>>> print(request.headers)
...

我还注意到,当页面回复重定向状态码(例如 301)时,我得到的响应是重定向页面,而不是第一个(这是我想要的)。

知道我该怎么做吗?

【问题讨论】:

    标签: python httprequest urllib


    【解决方案1】:

    您是否考虑过使用 requests 包?它为您提供了为满足您的请求而进行的所有重定向的历史记录:

    >>> import requests
    >>> r = requests.get('http://google.com')
    >>> r
    <Response [200]>
    >>> r.history
    [<Response [301]>, <Response [302]>]
    >>> r.url
    u'http://www.google.co.uk/'
    

    它还可以很好地处理 401 错误

    >>> r = requests.get('http://sitesurgeon.co.uk/!dev/http-authorisation/staff/index.htm')
    >>> r
    <Response [401]>
    >>> r.content
    '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"> ...
    ....'
    >>> r.headers
    {'date': 'Wed, 06 Jun 2012 14:24:16 GMT', 'x-powered-by': 'PHP/5.3.13', 'transfer-encoding': 'chunked', 'content-type': 'text/html; charset=utf-8', 'www-authenticate': 'Basic realm="Staff Area"', 'server': 'Apache'}
    

    如果您想控制超时,只需按如下方式提出请求:

    requests.get('http://google.com', timeout=0.1)
    

    【讨论】:

    • 太好了,看起来像我要找的东西。在接受之前,你知道当主机宕机或不存在时的处理方法吗? r = requests.get('http://google.comm') 需要很长时间才会崩溃。
    • 很抱歉成为 requests 包的啦啦队长......但它真的很好用。使用 urllib2 很长时间了……但在使用 requests 5 分钟后感觉更好。
    • 我的意思是一个不存在的网站,例如 google.comm(两个'm')​​,但它实际上不是 404 回复,只是一个套接字连接失败,所以我应该先检查一下。
    猜你喜欢
    • 2021-08-07
    • 1970-01-01
    • 2013-06-28
    • 2012-12-08
    • 2012-06-12
    • 2021-09-21
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    相关资源
    最近更新 更多