【问题标题】:Python requests exception handling: How to get more verbose (user-friendly) error message?Python 请求异常处理:如何获取更详细(用户友好)的错误消息?
【发布时间】: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


    【解决方案1】:

    我找到了您需要的短信 - 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)
    

    【讨论】:

      猜你喜欢
      • 2012-10-08
      • 1970-01-01
      • 2011-02-16
      • 1970-01-01
      • 1970-01-01
      • 2014-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多