[英]urllib3 how to find code and message of Http error
我正在使用python捕获HTTP错误,但我想知道该错误的代码(例如400、403,..)。 另外,我想获得错误消息。 但是,我在文档中找不到这两个属性。 有人可以帮忙吗? 谢谢。
try:
"""some code here"""
except urllib3.exceptions.HTTPError as error:
"""code based on error message and code"""
假设您是在说“错误消息”时指的是HTTP响应的描述,则可以使用来自http.client
responses
,如以下示例所示:
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
在我的例子中。
希望对您有所帮助。 问候。
以下示例代码说明了响应的状态代码和错误原因:
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)
状态码来自响应,而HTTPError表示urllib3无法获取响应。 状态码400+不会触发urllib3的任何异常。
为什么要捕获它作为例外? 您希望看到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以获取更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.