对于新手问题,提前致歉。我刚刚学习如何使用 Python 访问 Web 数据,但我无法理解 requests
包中的异常处理。
到目前为止,当使用 urllib
包访问网络数据时,我将 urlopen
调用包装在 try/except 结构中以捕获错误的 URL,如下所示:
import urllib, sys
url = 'https://httpbinTYPO.org/' # Note the typo in my URL
try: uh=urllib.urlopen(url)
except:
print 'Failed to open url.'
sys.exit()
text = uh.read()
print text
这显然是一种粗略的方法,因为它可以掩盖除错误 URL 之外的所有问题。
从文档中,我了解到在使用 requests
包时可以避免使用 try/except 结构,如下所示:
import requests, sys
url = 'https://httpbinTYPO.org/' # Note the typo in my URL
r = requests.get(url)
if r.raise_for_status() is not None:
print 'Failed to open url.'
sys.exit()
text = r.text
print text
但是,这显然不起作用(抛出错误和回溯)。执行此操作的“正确”(即简单、优雅、Pythonic)方法是什么?
最佳答案
try catch 连接错误:
from requests.exceptions import ConnectionError
try:
requests.get('https://httpbinTYPO.org/')
except ConnectionError:
print 'Failed to open url.'
关于python - 使用请求处理错误的 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38707394/