为什么第一个except ::子句不会捕获代理错误?我不太明白为什么它默认为第二个子句(或者如果我删除第二个原因它只会抛出错误)
from requests.exceptions import ProxyError
try:
login(acc)
except ProxyError:
pass
except Exception as e:
print e
Run Code Online (Sandbox Code Playgroud)
输出:
HTTPSConnectionPool(host='www.google.com', port=443): Max retries exceeded with url: /mail (Caused by ProxyError('Cannot connect to proxy.', error('Tunnel connection failed: 403 Forbidden',)))
Run Code Online (Sandbox Code Playgroud)
你在这里遇到了一些边缘情况.该ProxyError异常是不实际的requests.exceptions除外; 它是嵌入式urllib3库中具有相同名称的异常,它包含在MaxRetryError异常中.
这确实是一个错误,并且确实是在不久前提交的,请参阅问题#3050.它已通过此拉取请求修复,以提高正确的requests.exceptions.ProxyError异常.此修复程序已作为请求2.9.2的一部分发布.
通常,为您requests解开MaxRetryError异常,但不针对此特定异常.如果您无法升级到2.9.2或更高版本,您可以专门捕获它(现在解开两个层):
from requests.exceptions import ConnectionError
from requests.packages.urllib3.exceptions import MaxRetryError
from requests.packages.urllib3.exceptions import ProxyError as urllib3_ProxyError
try:
# ...
except ConnectionError as ce:
if (isinstance(ce.args[0], MaxRetryError) and
isinstance(ce.args[0].reason, urllib3_ProxyError)):
# oops, requests should have handled this, but didn't.
# see https://github.com/kennethreitz/requests/issues/3050
pass
Run Code Online (Sandbox Code Playgroud)
或者将拉取请求中的更改应用到本地安装requests.