Python+selenium 【第十二章】封装日志类-优化其他方法并添加日志(异常处理)
题记:
日志模块能够帮助我们快速定位到代码的错误地方,所有很有必要添加日志
- demo_log_24.py
1 # -*- coding: utf-8 -*- 2 # @Time : 2022/1/5 14:14 3 # @Author : Limusen 4 # @File : demo_log_24 5 6 # log日志demo 7 8 import os 9 import logging 10 import time 11 12 current_path = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) 13 logs_path = os.path.join(current_path, 'logs') 14 15 # logger输入的地址 16 login_name = os.path.join(logs_path, 'Test_%s.log' % time.strftime("%Y_%m_%d")) 17 18 # 创建logger对象 19 logger = logging.getLogger("logger") 20 # logger的等级 info 21 logger.setLevel(20) 22 23 fh = logging.FileHandler(login_name, 'a', encoding="utf-8") # 输出日志到文件 24 fh.setLevel(20) 25 ch = logging.StreamHandler() # 输出日志到控制台 26 ch.setLevel(20) 27 28 logger.addHandler(fh) 29 logger.addHandler(ch) 30 fh.close() # 关闭以免重复打印 31 ch.close() 32 33 logger.info("测试一下")
- 封装日志模块
- common模块新增log_utils.py
1 # -*- coding: utf-8 -*- 2 # @Time : 2022/1/5 14:13 3 # @Author : Limusen 4 # @File : log_utils 5 6 7 import os 8 import time 9 import logging 10 from common.config_utils import local_config 11 12 current_path = os.path.dirname(os.path.abspath(__file__)) 13 log_path = os.path.join(current_path, '..','logs') 14 15 16 class LogUtils: 17 18 def __init__(self, logger=None): 19 self.log_name = os.path.join(log_path, 'Test_%s.log' % time.strftime('%Y_%m_%d')) 20 self.logger = logging.getLogger(logger) # 日志对象 21 self.logger.setLevel(local_config.log_level) # 日志级别 22 23 self.fh = logging.FileHandler(self.log_name, 'a', encoding='utf-8') # 输出到文件 24 self.fh.setLevel(local_config.log_level) 25 self.ch = logging.StreamHandler() # 输出到控制台 26 self.ch.setLevel(local_config.log_level) 27 28 formatter = logging.Formatter( 29 '[%(asctime)s] %(filename)s->%(funcName)s line:%(lineno)d [%(levelname)s] : %(message)s') 30 self.fh.setFormatter(formatter) 31 self.ch.setFormatter(formatter) 32 self.logger.addHandler(self.fh) 33 self.logger.addHandler(self.ch) 34 self.fh.close() 35 self.ch.close() 36 37 def get_log(self): 38 return self.logger 39 40 41 logger = LogUtils().get_log() 42 43 if __name__ == '__main__': 44 logger.info('测试一下日志文件')
- 优化其他类,加入日志模块及异常处理
- base_page.py
1 # -*- coding: utf-8 -*- 2 # @Time : 2022/1/5 13:50 3 # @Author : Limusen 4 # @File : base_page 5 6 7 from selenium import webdriver 8 from selenium.webdriver.common.by import By 9 from selenium.webdriver.support.wait import WebDriverWait 10 from common.log_utils import logger 11 12 13 class BasePage: 14 15 def __init__(self, driver): 16 self.driver = driver 17 18 def open_url(self, url): 19 self.driver.get(url) 20 logger.info("当前正在打开网址: [%s]" % url) 21 22 def find_element(self, element_info): 23 """ 24 通过分离处理的元素识别字典信息,返回一个元素 25 :param element_info: 元素信息,字典类型{} 26 :return: element对象 27 """ 28 try: 29 locator_type = element_info["locator_type"] 30 locator_value = element_info["locator_value"] 31 locator_timeout = element_info["timeout"] 32 33 if locator_type == "name": 34 locator_type = By.NAME 35 elif locator_type == "css": 36 locator_type = By.CSS_SELECTOR 37 elif locator_type == "xpath": 38 locator_type = By.XPATH 39 elif locator_type == "id": 40 locator_type = By.ID 41 elif locator_type == "class": 42 locator_type = By.CLASS_NAME 43 elif locator_type == "linktext": 44 locator_type = By.LINK_TEXT 45 elif locator_type == "partiallink": 46 locator_type = By.PARTIAL_LINK_TEXT 47 elif locator_type == "tag": 48 locator_type = By.TAG_NAME 49 # 采用匿名函数 将元素存在x变量当中,然后去查找页面是否存在当前元素 50 element = WebDriverWait(self.driver, locator_timeout).until( 51 lambda x: x.find_element(locator_type, locator_value)) 52 logger.info("当前进行元素识别操作,元素名称为: [%s] " % (element_info["element_name"])) 53 except Exception as e: 54 logger.error("[%s]元素不能识别,原因是: %s" % (element_info['element_name'], e.__str__())) 55 raise 56 57 return element 58 59 def click(self, element_info): 60 # 优化 61 try: 62 element = self.find_element(element_info) 63 logger.info("当前进行点击操作,点击元素名称为: [%s] " % (element_info["element_name"])) 64 except Exception as e: 65 logger.error("当前元素不能点击,原因是: [%s]" % e.__str__()) 66 raise 67 element.click() 68 69 def send_keys(self, element_info, inputs): 70 # 优化 71 try: 72 element = self.find_element(element_info) 73 logger.info("输入框输入内容:%s ,识别输入元素:[%s]" % (inputs, element_info["locator_value"])) 74 except Exception as e: 75 logger.error("[%s]元素不能识别,原因是: %s" % (element_info['element_name'], e.__str__())) 76 raise 77 element.send_keys(inputs) 78 79 80 if __name__ == '__main__': 81 driver = webdriver.Chrome() 82 db = BasePage(driver) 83 db.open_url("http://www.baidu.com") 84 driver.implicitly_wait(10) 85 86 # 优化代码 读取excel中的数据 87 element_info = { 88 'input_text': {'element_name': '输入框', 'locator_type': 'xpath', 'locator_value': '//*[@id="kw"]', 89 'timeout': 5.0}, 90 'click_button': {'element_name': '点击按钮', 'locator_type': 'xpath', 'locator_value': '//*[@id="su"]', 91 'timeout': 5.0}} 92 93 input_t = element_info['input_text'] 94 click_b = element_info['click_button'] 95 96 db.send_keys(input_t, "测试一下") 97 db.click(click_b)
- browser_utils.py
1 # -*- coding: utf-8 -*- 2 # @Time : 2022/1/4 19:44 3 # @Author : Limusen 4 # @File : browser_utils 5 # 封装驱动类 6 7 import os 8 import sys 9 import warnings 10 from selenium import webdriver 11 from selenium.webdriver.chrome.options import Options 12 from common.config_utils import local_config 13 from common.log_utils import logger 14 15 current_path = os.path.dirname(os.path.abspath(__file__)) 16 system_driver = sys.platform 17 18 19 class BrowserUtils: 20 21 def __init__(self): 22 # 去除控制台警告 23 warnings.filterwarnings("ignore", category=DeprecationWarning) 24 self.driver_name = local_config.driver_name 25 26 def get_driver(self): 27 if self.driver_name.lower() == 'chrome': 28 logger.info("当前正在打开:%s" % self.driver_name) 29 return self.__get_chrome_driver() 30 elif self.driver_name.lower() == 'firefox': 31 logger.info("当前正在打开:%s" % self.driver_name) 32 return self.__get_firefox_driver() 33 elif self.driver_name.lower() == 'edge': 34 logger.info("当前正在打开:%s" % self.driver_name) 35 return self.__get_edge_driver() 36 37 def __get_chrome_driver(self): 38 # 先封装简易代码 39 # 加入系统环境判断 40 chrome_options = Options() 41 chrome_options.add_argument('--disable-gpu') # 谷歌文档提到需要加上这个属性来规避bug 42 chrome_options.add_argument('lang=zh_CN.UTF-8') # 设置默认编码为utf-8 43 chrome_options.add_experimental_option('useAutomationExtension', False) # 取消chrome受自动控制提示 44 chrome_options.add_experimental_option("excludeSwitches", ['enable-automation']) # 取消chrome受自动控制提示 45 if system_driver.lower() == "darwin": 46 """如果是mac系统执行这个驱动""" 47 chrome_path = os.path.join(current_path, '..', 'webdriver', 'chrome', 'chromedriver.exe') 48 driver = webdriver.Chrome(executable_path=chrome_path, options=chrome_options) 49 logger.info('初始化Google浏览器并启动') 50 return driver 51 else: 52 chrome_path = os.path.join(current_path, '..', 'webdriver', 'chrome', 'chromedriver93.exe') 53 driver = webdriver.Chrome(executable_path=chrome_path, options=chrome_options) 54 logger.info('初始化Google浏览器并启动') 55 return driver 56 57 def __get_firefox_driver(self): 58 if system_driver.lower() == "darwin": 59 firefox_path = os.path.join(current_path, '..', 'webdriver', 'firefox', 'geckodriver') 60 driver = webdriver.Firefox(executable_path=firefox_path) 61 logger.info('初始化Firefox浏览器并启动') 62 return driver 63 else: 64 firefox_path = os.path.join(current_path, '..', 'webdriver', 'firefox', 'geckodriver.exe') 65 driver = webdriver.Firefox(executable_path=firefox_path) 66 logger.info('初始化Firefox浏览器并启动') 67 return driver 68 69 def __get_edge_driver(self): 70 """ 71 驱动下载地址:https://developer.microsoft.com/zh-cn/microsoft-edge/tools/webdriver/ 72 :return: 73 """ 74 edge_path = os.path.join(current_path, '..', 'webdriver', 'edge', 'msedgedriver.exe') 75 driver = webdriver.Edge(executable_path=edge_path) 76 logger.info('初始化Edge浏览器并启动') 77 return driver 78 79 80 if __name__ == '__main__': 81 driver = BrowserUtils().get_driver() 82 driver.get("https://www.baidu.com")
总结:
本章节主要讲的是日志模块如何封装及使用,部分代码内容进行异常处理,下一章节我们将进行实战操作,针对iweb商城进行实操,从登陆到下单的操作