Python 当无法访问网页时,如何继续执行脚本?
需要做的是,如果可以访问10.10.10.2,则程序应Python 当无法访问网页时,如何继续执行脚本?,python,python-3.x,if-statement,urllib,Python,Python 3.x,If Statement,Urllib,需要做的是,如果可以访问10.10.10.2,则程序应退出(),但如果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")
退出()
,但如果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
。这会在给定的时间后引发一个URL错误。您可以捕捉到这个错误
带着
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")