Python请求异常处理:如何获得更详细(用户友好)的错误消息?

时间:2015-10-31 06:59:12

标签: python exception exception-handling python-requests

假设我有一些功能:

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 ='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',))
...

所以我只想打印错误消息的“最后一部分”。在第一种情况下“没有与主机名相关联的地址”,第二种“名称或服务未知”

1 个答案:

答案 0 :(得分:0)

我找到了您需要的短信 - e.args[0].args[1].args[1]。它不清楚,但它打印:

Connection to http://google failed. 
 No address associated with hostname

代码:

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.args[0].args[1].args[1])
        sys.exit(0)