请告诉我是否发现可能的错误?
import requests
try:
req = requests.get('http://google.com')
except FileNotFoundError as exc:
print('Error open url. ', exc)
或FileNotFoundError仅适用于文件系统中的文件?在这种情况下,我仍然使用上述代码的什么类型的异常?
答案 0 :(得分:2)
Here是requests
库引发的异常列表。 FileNotFoundError
不在其中。
您应该执行以下操作:
import requests
try:
req = requests.get('http://google.com')
except requests.exceptions.HTTPError as exc:
print('HTTP error', exc)
您可以根据需要捕捉其他例外情况:
Python 3.3.2+ (default, Oct 9 2013, 14:50:09)
>>> import requests
>>> requests.get('googleeeeeeee2323235.com')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
...
"Perhaps you meant http://{0}?".format(url))
requests.exceptions.MissingSchema: Invalid URL 'googleeeeeeee2323235.com': No schema supplied. Perhaps you meant http://googleeeeeeee2323235.com?
>>> requests.get('http://googleeeeeeee2323235.com')
Traceback (most recent call last):
...
File "/usr/lib/python3.3/socket.py", line 417, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
socket.gaierror: [Errno -2] Name or service not known
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
...
raise MaxRetryError(self, url, e)
requests.packages.urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='googleeeeeeee2323235.com', port=80): Max retries exceeded with url: / (Caused by <class 'socket.gaierror'>: [Errno -2] Name or service not known)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
...
raise ConnectionError(e)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='googleeeeeeee2323235.com', port=80): Max retries exceeded with url: / (Caused by <class 'socket.gaierror'>: [Errno -2] Name or service not known)
>>>
因此,如果主机未知,您应该抓住requests.exceptions.ConnectionError
。
或者您可能希望捕获所有requests
例外的基本例外。查阅文档或源代码以了解它是什么。