Python 从 requests.exceptions.HTTPError 获取 HTTP 错误代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19342111/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:31:11 来源:igfitidea点击:
Get HTTP Error code from requests.exceptions.HTTPError
提问by Shiplu Mokaddim
I am catching exceptions like this,
我正在捕捉这样的异常,
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.
采纳答案by Lukasa
The HTTPError
carries the Response
object with it:
的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
回答by Raj
This is my code to get errors codes in HTTP
这是我在 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)