2017-10-20 90 views
0

我使用蟒蛇捕获HTTP错误代码和消息,但我想知道的错误(例如400,403,...)的代码。另外,我想获得错误信息。但是,我无法在文档中找到这两个属性。谁能帮忙?谢谢。urllib3如何找到HTTP错误

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

回答

0

你为什么把它作为异常?你想看到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获取更多信息。

0

假设你指的是HTTP响应的描述时,表示“错误的消息”,则可以在下面的示例中使用responseshttp.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 

对我的例子。

我希望它有帮助。问候。