【发布时间】:2015-10-31 06:59:12
【问题描述】:
假设我有一些功能:
def get_result(url):
try:
return requests.get(url, headers={'User-Agent': random.choice(USER_AGENTS)}).text
except requests.exceptions.ConnectionError as e:
message = 'Connection to {0} failed. \n {1}'
print message.format(url, e)
sys.exit(0)
案例 #1 “错误的 url 语法” url = 'http://google'
...
connection to http://google failed.
HTTPConnectionPool(host='google', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x7fd417ece350>: Failed to establish a new connection: [Errno -5] No address associated with hostname',))
...
案例#2“不存在的网址” url = 'http://smth_non_existing.com'
...
connection to http://smth_non_existing.com failed.
HTTPConnectionPool(host='smth_non_existing.com', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x7fe196d4a3d0>: Failed to establish a new connection: [Errno -2] Name or service not known',))
...
所以我只想打印错误消息的“最后一部分”。第一种情况“没有与主机名关联的地址”,第二种情况“名称或服务未知”
【问题讨论】:
标签: python exception exception-handling python-requests