从 requests.exctions.HTTPError 获取 HTTP 错误代码

我在抓这样的例外,

def get_url_fp(image_url, request_kwargs=None):
response = requests.get(some_url, **request_kwargs)
response.raise_for_status()
return response.raw




try:
a = "http://example.com"
fp = get_url_fp(a)


except HTTPError as e:
# Need to check its an 404, 503, 500, 403 etc.
86925 次浏览

HTTPError携带着 Response对象:

def get_url_fp(image_url, request_kwargs=None):
response = requests.get(some_url, **request_kwargs)
response.raise_for_status()
return response.raw




try:
a = "http://example.com"
fp = get_url_fp(a)


except HTTPError as e:
# Need to check its an 404, 503, 500, 403 etc.
status_code = e.response.status_code

这是我在 HTTP 中获取错误代码的代码

def tomcat_status(ip,port,url):
try:
# you can give your own url is
r = urllib2.urlopen('http://'+ip+':'+port+'/'+url)
return r.getcode()
except urllib2.HTTPError as e:
return e.code
except urllib2.URLError as f:
return 1
print tomcat_status(ip,tomcat_port,ping_url)

如果只需要 status _ code 或者 message error,可以使用以下代码:

try:
[YOUR CODE]
except requests.exceptions.HTTPError as err:
print(err.response.status_code)
print(err.response.text)

参考文献: requests.eption 的源代码