Skip to main content
 首页 » 编程设计

Python 3之urllib.request之HTTPError

2024年12月31日13emanlee

    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。

当我使用网络服务器的 IP 运行它时,我恢复了服务器在线。

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

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

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

请您参考如下方法:

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