【问题标题】:Python 3 - urllib.request - HTTPErrorPython 3 - urllib.request - HTTPError
【发布时间】:2018-06-25 13:53:30
【问题描述】:
    import urllib.request
request = urllib.request.Request('http://1.0.0.8/')
try:
    response = urllib.request.urlopen(request)
    print("Server Online")
    #do stuff here
except urllib.error.HTTPError as e: # 404, 500, etc..
    print("Server Offline")
    #do stuff here

我正在尝试编写一个简单的程序来检查 LAN 网络服务器列表是否已启动。目前只使用一个IP。

当我使用 Web 服务器的 IP 运行它时,我会返回 Server Online。

当我使用没有网络服务器的 IP 运行它时,我得到了

"urllib.error.URLError: <urlopen error [WinError 10061] No connection could be made because the target machine actively refused it>" 

但宁愿一个简单的“服务器离线”输出。不知道如何获得对输出 Server Offline 的回复。

【问题讨论】:

    标签: python python-3.x urllib


    【解决方案1】:

    在上面的代码中,您只是在寻找 HTTPError 异常。 只需在末尾添加另一个 except 子句,该子句将引用您正在查找的异常,在本例中为 URLError:

    import urllib.request
    request = urllib.request.Request('http://1.0.0.8/')
    try:
        response = urllib.request.urlopen(request)
        print("Server Online")
        #do stuff here
    except urllib.error.HTTPError as e:
         print("Server Offline")
         #do stuff here
    except urllib.error.URLError as e:
         print("Server Offline")
         #do stuff here
    

    【讨论】:

    • 这里的关键是将HTTPError 放在URLError 之前,这样“子异常”就会首先引发。
    【解决方案2】:

    好吧,我们也可以合并错误。

    except (urllib.error.URLError, urllib.error.HTTPError):
         print("Poor server is offline.")
    

    【讨论】:

      猜你喜欢
      • 2021-04-21
      • 1970-01-01
      • 2014-10-04
      • 1970-01-01
      • 1970-01-01
      • 2013-01-27
      • 2013-03-28
      • 2011-04-14
      • 2018-05-24
      相关资源
      最近更新 更多