# 线上巡检 :有一个虚拟人,在不断地检测线上系统的功能是否正常(自动化技术实现) import json from time import sleep from jsonpath import jsonpath from selenium import webdriver from selenium.webdriver import DesiredCapabilities # from selenium.webdriver.chrome.options import Options from base_page.webdriver import send_qiye_wechat_msg chrome_options = webdriver.ChromeOptions() chrome_options.add_experimental_option("w3c", True) chrome_options.add_argument("--disk-cache-size=0") #关闭浏览器缓存 # chrome_options.add_argument('--headless') #无头模式 # driver = webdriver.Chrome(options=chrome_options) caps = DesiredCapabilities.CHROME caps['goog:loggingPrefs'] = {'performance': 'ALL'} #开启获取日志的功能--需要去看浏览器的官方文档说明 driver = webdriver.Chrome(options=chrome_options) #初始化浏览器,,desired_capabilities=caps 开启日志功能 driver.maximize_window() #最大化浏览器 driver.get("http://192.168.239.130/opencart/")# 打开网址 # sleep(5) #等待页面元素加载,强制等待 driver.implicitly_wait(10) #隐式等待 print("开始线上巡检") while True: #以下代码会反复运行多次 sleep(3) #每次运行间隔3s driver.execute_cdp_cmd("Page.reload", {"ignoreCache": True}) # 忽略页面缓存强制刷新获取最新页面 print('刷新页面') logs = driver.get_log("performance") #获取到浏览器的日志 for log in logs: #循环,拆分出所有logs中的每一条log,每一条单独的log都是字典 #解析浏览器日志,分析是否有500这种报错的网络请求 json_log = json.loads(log["message"]) #json.loads()对括号中的数据json化 ,log["message"]取出当前日志中的message对应的值 if json_log['message']['method'] != 'Network.responseReceived': #判断son_log[]中的message下method的方法中不包含服务器的响应信息 continue #如果不是服务器响应信息,逃过不处理 print('当前的日志是', json_log) status = jsonpath(json_log, '$..status')[0] # $符号代表最外层的{ ,取出对应的服务器响应状态码递归下降(..):递归下降运算符允许在 JSON 结构中向下递归搜索。例如,$..book 表示访问 JSON 结构中的所有 book 属性,无论它们位于何处。 print(status) if status >= 500: #服务器响应状态码大于或等于500 driver.save_screenshot('a.png') #保存当前页面截图 driver.quit() send_qiye_wechat_msg('a.png') #发送消息到企业微信,,自己封装方法调用企业微信 print('检测到当前页面打开有网络错误') raise Exception('线上系统出问题了') sleep(3) driver.quit()
线上巡检 :
最新推荐文章于 2024-07-12 16:16:27 发布