urllib3如何查找Http错误的代码和消息

时间:2017-10-20 07:08:36

标签: python exception-handling urllib3

我正在使用python捕获http错误,但我想知道错误的代码(例如400,403,..)。另外,我想得到错误的消息。但是,我在文档中找不到这两个属性。有人可以帮忙吗?谢谢。

    try:
        """some code here"""
    except urllib3.exceptions.HTTPError as error:
        """code based on error message and code"""

4 个答案:

答案 0 :(得分:0)

假设您在说出“错误消息”时表示HTTP响应,您可以使用responses中的http.client,如下例所示:

import urllib3
from http.client import responses

http = urllib3.PoolManager()
request = http.request('GET', 'http://google.com')

http_status = request.status
http_status_description = responses[http_status]

print(http_status)
print(http_status_description)

......执行时会给你:

200
OK

就我的例子而言。

我希望它有所帮助。问候。

答案 1 :(得分:0)

以下示例代码说明了响应的状态代码和错误原因:

import urllib3
try:
  url ='http://httpbin.org/get'
  http = urllib3.PoolManager()
  response=http.request('GET', url)
  print(response.status)
except urllib3.exceptions.HTTPError as e:
  print('Request failed:', e.reason)

答案 2 :(得分:0)

状态码来自响应,而HTTPError表示urllib3无法获取响应。状态代码400+不会触发urllib3的任何异常。

答案 3 :(得分:-1)

你为什么把它当作例外?您希望看到http响应,因此您不需要将其作为例外处理。

您可以简单地发出HTTP请求并阅读如下响应:

import urllib3
http = urllib3.PoolManager()
req = http.request('GET', 'http://httpbin.org/robots.txt')
status_code = req.status
server_response = req.data

查看urllib3 readthedocs了解详情。