我使用 Python 2.7 来执行启动浏览器、验证 header 并关闭浏览器的简单任务
#Launch the browser @ google
new = 0
url = "http://www.google.com/"
webbrowser.open(url, new=new)
#Check for the header
conn = httplib.HTTPConnection("www.google.com")
conn.request("HEAD", "/")
r1 = conn.getresponse()
#Close the browser
os.system("taskkill /im iexplore.exe")
这只是在无限循环上运行,以验证连续连接。 Ping 检查不足以满足我需要的流量,否则我会使用它。
我的问题是,如果我确实失去了连接,脚本就会卡住并且出现地址信息错误。我如何忽略它,或识别它,终止浏览器并保持脚本运行?
抱歉,如果我做得不对......这是我的第一篇文章。
最佳答案
我认为您实际上根本不需要浏览器。
同时,忽略或识别错误的方法是使用 try
语句。所以:
while True:
try:
conn = httplib.HTTPConnection("www.google.com")
conn.request("HEAD", "/")
r1 = conn.getresponse()
if not my_verify_response_func(r1):
print('Headers are wrong!')
except Exception as e:
print('Failed to check headers with {}'.format(e))
time.sleep(60) # I doubt you want to run as fast as possible
关于Python 浏览器启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19282936/