0
讓我們假設我有一些功能:Python請求異常處理:如何獲取更詳細的(用戶友好的)錯誤消息?
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',))
...
所以我只想打印錯誤消息的'最後部分'。在第一種情況下「沒有地址與主機名相關」和第二個「名稱或服務不知道」