简体   繁体   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

I'm trying to write a simple program that will check a list of LAN webserver is up.我正在尝试编写一个简单的程序来检查 LAN 网络服务器列表是否已启动。 Currently just using one IP for now.目前只使用一个 IP。

When I run it with an IP of a web server I get back Server Online.当我使用 Web 服务器的 IP 运行它时,我会返回 Server Online。

When I run it with a IP that doesn't have web server I get当我使用没有网络服务器的 IP 运行它时,我得到

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

but would rather a simple "Server Offline" output.而是一个简单的“服务器离线”输出。 Not sure how to get the reply to output Server Offline.不确定如何获得对输出服务器脱机的答复。

In your code above you're just looking for HTTPError exceptions.在上面的代码中,您只是在寻找 HTTPError 异常。 Just add another except clause to the end that would reference the exception that you are looking for, in this case the URLError:只需在末尾添加另一个 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

well, we could combine the errors as well.好吧,我们也可以合并错误。

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