requests.HTTPError 在 requests.get() 404 响应后未被捕获 [英] requests.HTTPError uncaught after a requests.get() 404 response

查看:28
本文介绍了requests.HTTPError 在 requests.get() 404 响应后未被捕获的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的请求库有点问题.

举个例子,我在 Python 中有一个这样的语句:

Say for example I have a statement like this in Python:

try:
   request = requests.get('google.com/admin') #Should return 404

except requests.HTTPError, e:
   print 'HTTP ERROR %s occured' % e.code

由于某种原因,异常没有被捕获.我已经检查了请求的 API 文档,但它有点苗条.有没有人对图书馆有更多的经验可以帮助我?

For some reason the exception is not being caught. I've checked the API documentation for requests but it's a bit slim. Is there anyone who has more experience with the library that might be able to help me out?

推荐答案

口译员是你的朋友:

import requests
requests.get('google.com/admin')
# MissingSchema: Invalid URL u'google.com/admin': No schema supplied

此外,requests 异常:

import requests.exceptions
dir(requests.exceptions)

还要注意,如果状态不是 200,默认情况下 requests 不会引发异常:

Also notice that by default requests doesn't raise exception if status is not 200:

In [9]: requests.get('https://google.com/admin')
Out[9]: <Response [503]>

raise_for_status() 方法可以做到这一点:

There is raise_for_status() method that does it:

In [10]: resp = requests.get('https://google.com/admin')

In [11]: resp
Out[11]: <Response [503]>

In [12]: resp.raise_for_status()
  ...
HTTPError: 503 Server Error: Service Unavailable

这篇关于requests.HTTPError 在 requests.get() 404 响应后未被捕获的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆