1.利用Python+selenium框架对网页元素进行检测,元素能被找到说明网页显示正常,若元素无法被定位,则网页已经异常显示,连续三次检测都异常,便触发钉钉消息报警
2.代码如下
function.py
# coding=utf-8
import os
import traceback
import time
from selenium import webdriver
import requests
from selenium.common.exceptions import NoSuchElementException
from selenium import webdriver
#要检测的元素
master_check_xpath = "//*[@id='__layout']/div/div[2]/div/div[2]/h6"
turbo_check_xpath = "/html/body/div[1]/div/div[1]/div/div[2]/span[1]"
monster_check_xpath = "/html/body/section[1]/div[2]/a"
check_xpath=[master_check_xpath,turbo_check_xpath,monster_check_xpath]
#钉钉群机器人webhook地址
DINGDING_URL_WEBHOOK = "https://oapi.dingtalk.com/robot/send?access_token=xxxxxxxxxxxx025a8b26f7fef564fdf8a9836196c8f3390094b0d02"
CWD = os.path.dirname(os.path.realpath(__file__))
chromedriver = '%s/chromedriver' % CWD
#要监控的网站
url_list = [
"https://www.xxxxx.com/",
"https://www.vvvvvv.co/",
"https://www.fffff.co/"
]
#检测函数
def check(url, check_xpath):
driver = webdriver.Firefox()
try:
driver.get(url)
print("check website is ", url)
driver.maximize_window()
driver.implicitly_wait(30)
time.sleep(40)
result = isElementPresent(driver, check_xpath)
driver.quit()
print(result)
return result
except:
print("except")
finally:
driver.quit()
#判断元素是否存在
def isElementPresent(driver, value):
try:
element = driver.find_element_by_xpath(value)
except NoSuchElementException as e:
return False
else:
return True
#钉钉报警函数
def DingDingalert(msg):
"""
send alert info by DingDing
:param msg:
:return:
"""
data = {
'msgtype': 'text',
'text': {
"content": msg
},
}
try:
return requests.post(DINGDING_URL_WEBHOOK, json=data)
except:
traceback.print_exc()
main.py
# coding=utf-8
from function import *
import datetime
if __name__ == '__main__':
#保证循环检测
while 1:
for i in range(len(url_list)):
print("starttime", datetime.datetime.now())
result = check(url_list[i], check_xpath[i])
if result:
print("checkresult is ok")
else:
print(url_list[i])
time.sleep(10)
second_result = check(url_list[i], check_xpath[i])
if second_result == False:
time.sleep(20)
print(url_list[i])
third_second = check(url_list[i], check_xpath[i])
if third_second == False:
msg = url_list[i] + " 崩溃了!!!"
print(msg)
DingDingalert(msg)
else:
break
else:
break