如何在无法访问网页时继续执行脚本?

How to continue execution of a script when a webpage is not reachable?

需要做的是,如果 10.10.10.2 可以访问,程序应该 exit(),但是如果 10.10.10.2 在 10 秒内无法访问,192.168.100.5 将被打开,程序将继续。 ..

有人可以举一个小例子说明如何做到这一点吗?

import urllib.request
import eventlet
from xml.dom import minidom
import urllib.request

preflash = urllib.request.urlopen("http://10.10.10.2").getcode()
correct = urllib.request.urlopen("http://192.168.100.5").getcode()

print(100*"#")

#eventlet.monkey_patch()
#with eventlet.Timeout(10):

if True:
    print("Web page status code:",preflash)
    print("Web page is reachable")
else:
    print("Web page status code:", correct)
    print("Web page is reachable")
url_str = 'http://192.168.100.2/globals.xml'

# open webpage and read values
xml_str = urllib.request.urlopen(url_str).read()

# Parses XML doc to String for Terminal output
xmldoc = minidom.parseString(xml_str)

# Finding the neccassary Set points/ Sollwerte from the xmldoc

# prints the order_number from the xmldoc
order_number = xmldoc.getElementsByTagName('order_number')
print("The Order number of the current device is:", order_number[0].firstChild.nodeValue)
print(100*"-")

使用 timeout 参数调用 urlopen。这会在给定时间后引发 URLError。你可以捕获这个错误 try ... except block

import urllib

try:
    preflash = urllib.request.urlopen("http://10.10.10.2", timeout=10).getcode()
    print("Web page status code:", preflash)
    print("Web page is reachable")
except urllib.error.URLError:
    correct = urllib.request.urlopen("http://192.168.100.5").getcode()
    print("Web page status code:", correct)
    print("Web page is reachable")