gpt4 book ai didi

python - requests.HTTPError 在 requests.get() 404 响应后未被捕获

转载 作者:行者123 更新时间:2023-11-28 19:37:31 26 4
gpt4 key购买 nike

请求库有点问题。

例如,我在 Python 中有这样一条语句:

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

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

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

最佳答案

口译员是你的 friend :

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

此外,请求异常:

import requests.exceptions
dir(requests.exceptions)

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

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

raise_for_status()实现方法:

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

关于python - requests.HTTPError 在 requests.get() 404 响应后未被捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16206062/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com