gpt4 book ai didi

使用 selenium 处理 Python 异常

转载 作者:太空宇宙 更新时间:2023-11-03 17:09:37 26 4
gpt4 key购买 nike

我是Python新手,我正在尝试编写一个nagios脚本,它使用selenium登录到web应用程序并打印出一些信息。到目前为止,脚本按预期工作,但我希望它在无法检索网站时向系统发出警报。这是我所拥有的

#!/usr/bin/env python

import sys
from selenium import webdriver

url = '<main web site>'
systemInformation = '<sys information site>'
logout = '<log out link>'
browser = webdriver.PhantomJS('<path to phantomjs for headless operation>')
login_username = '<username>'
login_password = '<password>'

try:
browser.get(url)
username = browser.find_element_by_name("username")
password = browser.find_element_by_name("password")

username.send_keys(login_username)
password.send_keys(login_password)

link = browser.find_element_by_name('loginbutton')
link.click()

browser.get(systemInformation)

print "OK: Web Application is Running"
for element in browser.find_elements_by_name('SystemReportsForm'):
print element.text

browser.get(logout)
browser.quit()
sys.exit(0)
except:
print "WARNING: Web Application is Down!"
sys.exit(2)

我希望如果第一部分失败,它将转到 except 部分,但是即使存在退出,脚本也会打印出 try 和 except 。我确信我缺少一些简单的东西。

提前致谢

更新

这就是我最终解决这个问题的方法,感谢您的帮助

#!/usr/bin/env python

import sys, urllib2
from selenium import webdriver

url = '<log in url>'
systemInformation = '<sys info url>'
logout = '<logout url>'
browser = webdriver.PhantomJS('<phantomjs location for headless browser>')
login_username = '<user>'
login_password = '<password>'

def login(login_url,status_url):
browser.get(login_url)
username = browser.find_element_by_name("username")
password = browser.find_element_by_name("password")

username.send_keys(login_username)
password.send_keys(login_password)

link = browser.find_element_by_name('loginbutton')
link.click()

browser.get(status_url)

if browser.title == 'Log In':
print "WARNING: Site up but Failed to login!"
browser.get(logout)
browser.quit()
sys.exit(1)
else:
print "OK: Everything Looks Good"
for element in browser.find_elements_by_name('SystemReportsForm'):
print element.text

browser.get(logout)
browser.quit()
sys.exit(0)

req = urllib2.Request(url)

try:
urllib2.urlopen(req)
login(url,systemInformation)
except urllib2.HTTPError as e:
print('CRITICAL: Site Appears to be Down!')
browser.get(logout)
browser.quit()
sys.exit(2)

最佳答案

sys.exit([status]) 引发 SystemExit(status) 异常,这就是执行 except 子句的原因

Exit the interpreter by raising SystemExit(status). If the status is omitted or None, it defaults to zero (i.e., success). If the status is an integer, it will be used as the system exit status. If it is another kind of object, it will be printed and the system exit status will be one (i.e., failure).

删除try内的sys.exit(0)
(如果您显示了脚本的完整版本)

关于使用 selenium 处理 Python 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34232957/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com