繁体   English   中英

Python 3 - urllib.request - HTTPError

[英]Python 3 - urllib.request - HTTPError

    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>" 

而是一个简单的“服务器离线”输出。 不确定如何获得对输出服务器脱机的答复。

在上面的代码中,您只是在寻找 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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM