Python+selenium 【第九章】封装config类/驱动类
前情提要
上一章节我们说到的是对页面元素的excel读取以及封装,讲到了操作excel操作,本章节将告诉读者如何让脚本自动执行属于不同系统的浏览器驱动,封装配置文件库,方便数据读取
什么是ini文件
首先我们要了解一下ini文件:
使用配置文件来灵活的配置一些参数是一件很常见的事情,配置文件的解析并不复杂,在python里更是如此,在官方发布的库中就包含有做这件事情的库,那就是configParser
configParser解析的配置文件的格式比较象ini的配置文件格式,就是文件中由多个section构成,每个section下又有多个配置项
ini文件格式
注意: section不能重复,里面数据通过section去查找,每个seletion下可以有多个key和vlaue的键值对,注释用英文分号( ; )
[section0]
key0 = value0
key1 = value1
[section1]
key2 = value2
key3 = value3
如何读取ini文件
python3里面自带configparser模块来读取ini文件
- 设置配置文件
新建conf.ini
# 配置文件处理
[DEFAULT]
# 测试网站主页面
URL = http://shop.aircheng.com/
# 默认等待时间
TIME_OUT = 5
- ini文件配置
- 新建config_utils.py文件
# -*- coding: utf-8 -*-
# @Time : 2022/1/4 19:34
# @Author : Limusen
# @File : config_utils
import os
import configparser
current_path = os.path.dirname(os.path.abspath(__file__))
conf_path = os.path.join(current_path, '..', 'config', 'config.ini')
class ConfigUtils:
def __init__(self):
self.cfg = configparser.ConfigParser()
self.cfg.read(conf_path, encoding="utf-8")
@property
def get_host(self):
return self.cfg.get("DEFAULT", "url")
@property
def time_out(self):
return self.cfg.get("DEFAULT","time_out")
local_config = ConfigUtils()
print(local_config.time_out)
print(local_config.get_host)
- config_utils.py
优化读取测试类中的超时时间
# -*- coding: utf-8 -*-
# @Time : 2022/1/4 17:06
# @Author : Limusen
# @File : element_excel_utils
import os
import xlrd3
from common.config_utils import local_config
# 元素识别信息读取工具类
current_path = os.path.dirname(__file__)
excel_path = os.path.join(current_path, '..', 'element_info_datas')
class ElementExcelUtils:
def __init__(self, module_name, page_name, element_path=excel_path):
"""
优化根据模块名读取excel内容
:param module_name: 模块内容 在element_info_datas下的模块
:param page_name: 登录页面 login_page1.py
:param excel_path: 查找当前路径下
"""
self.excel_path = os.path.join(element_path, module_name, page_name + '.xls')
# 创建excel对象
self.work_book = xlrd3.open_workbook(self.excel_path)
# 创建表单对象
self.sheet = self.work_book.sheet_by_index(0)
# 获取总行数
self.row_count = self.sheet.nrows
def get_element_info(self):
info_elements = {}
for info in range(1, self.row_count):
# 取出每行然后进行拼接处理
element_info = {}
element_info['element_name'] = self.sheet.cell_value(info, 1)
element_info['locator_type'] = self.sheet.cell_value(info, 2)
element_info['locator_value'] = self.sheet.cell_value(info, 3)
timeout_value = self.sheet.cell_value(info, 4)
# 如果超时时间为浮点型则直接使用timeout_value 如果为空则使用数字5
element_info['timeout'] = timeout_value if isinstance(timeout_value, float) else local_config.time_out
info_elements[self.sheet.cell_value(info, 0)] = element_info
return info_elements
if __name__ == '__main__':
ex = ElementExcelUtils("login", "login_page").get_element_info()
print(ex)
for i in ex.items():
print(i)
- element_excel_utils
封装驱动类
由于我们执行selenium每次都需要创建driver对象,代码太过冗余所以将驱动类单独封装,方便其他模块调用
这里我们需要用到os模块跟系统模块sys
1.os模块需要获取我们存放驱动的路径
2.sys模块主要是为了让脚本区分当前是在windows还是mac环境
- demo_browser_22.py
# -*- coding: utf-8 -*-
# @Time : 2022/1/4 19:46
# @Author : Limusen
# @File : demo_browser_22
import os
from selenium import webdriver
# 引入系统类
import sys
# 获取项目顶层路径
current_path = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
# print(current_path)
# 谷歌驱动地址
chrome_path = os.path.join(current_path, 'webdriver', 'chrome', 'chromedriver93.exe')
# print(chrome_path)
# 火狐驱动地址
firefox_path = os.path.join(current_path, 'webdriver', 'firefox', 'geckodriver.exe')
# print(firefox_path)
# edge驱动地址
edge_path = os.path.join(current_path, 'webdriver', 'edge', 'msedgedriver.exe')
# print(edge_path)
# driver = webdriver.Chrome(executable_path=chrome_path)
# driver.get("https://www.baidu.com")
#
# driver = webdriver.Firefox(executable_path=firefox_path)
# driver.get("https://www.baidu.com")
#
# driver = webdriver.Edge(executable_path=edge_path)
# driver.get("https://www.baidu.com")
# 可以判断当前是mac还是windows
system_driver = sys.platform
if system_driver.lower() == "darwin":
print("当前是mac环境")
else:
print("当前是windows环境")
- demo_browser_22.py
先封装简单一点的代码
- 新建browser_utils.py
# -*- coding: utf-8 -*-
# @Time : 2022/1/4 19:44
# @Author : Limusen
# @File : browser_utils
# 封装驱动类
import os
import sys
from selenium import webdriver
from common.config_utils import local_config
current_path = os.path.dirname(os.path.abspath(__file__))
system_driver = sys.platform
class BrowserUtils:
def __init__(self):
self.driver_name = local_config.driver_name
def get_chrome_driver(self):
# 先封装简易代码
chrome_path = os.path.join(current_path, '..', 'webdriver', 'chrome', 'chromedriver93.exe')
driver = webdriver.Chrome(executable_path=chrome_path)
return driver
def get_firefox_driver(self):
firefox_path = os.path.join(current_path, '..', 'webdriver', 'firefox', 'geckodriver.exe')
driver = webdriver.Firefox(executable_path=firefox_path)
return driver
def get_edge_driver(self):
edge_path = os.path.join(current_path, '..', 'webdriver', 'edge', 'msedgedriver.exe')
driver = webdriver.Edge(executable_path=edge_path)
return driver
if __name__ == '__main__':
driver = BrowserUtils().get_edge_driver()
driver.get("https://www.baidu.com")
继续封装,通过一个方法调用不同的驱动,做成私有化
在config.ini文件当中新增驱动chrome
# -*- coding: utf-8 -*-
# @Time : 2022/1/4 19:44
# @Author : Limusen
# @File : browser_utils
# 封装驱动类
import os
import sys
from selenium import webdriver
from common.config_utils import local_config
current_path = os.path.dirname(os.path.abspath(__file__))
system_driver = sys.platform
class BrowserUtils:
def __init__(self):
self.driver_name = local_config.driver_name
def get_driver(self):
if self.driver_name.lower() == 'chrome':
return self.__get_chrome_driver()
elif self.driver_name.lower() == 'firefox':
return self.__get_firefox_driver()
elif self.driver_name.lower() == 'edge':
return self.__get_edge_driver()
def __get_chrome_driver(self):
# 先封装简易代码
chrome_path = os.path.join(current_path, '..', 'webdriver', 'chrome', 'chromedriver93.exe')
driver = webdriver.Chrome(executable_path=chrome_path)
return driver
def __get_firefox_driver(self):
firefox_path = os.path.join(current_path, '..', 'webdriver', 'firefox', 'geckodriver.exe')
driver = webdriver.Firefox(executable_path=firefox_path)
return driver
def __get_edge_driver(self):
edge_path = os.path.join(current_path, '..', 'webdriver', 'edge', 'msedgedriver.exe')
driver = webdriver.Edge(executable_path=edge_path)
return driver
if __name__ == '__main__':
driver = BrowserUtils().get_driver()
driver.get("https://www.baidu.com")
加入系统判断 区分当前是windows还是mac
# -*- coding: utf-8 -*-
# @Time : 2022/1/4 19:44
# @Author : Limusen
# @File : browser_utils
# 封装驱动类
import os
import sys
from selenium import webdriver
from common.config_utils import local_config
current_path = os.path.dirname(os.path.abspath(__file__))
system_driver = sys.platform
class BrowserUtils:
def __init__(self):
self.driver_name = local_config.driver_name
def get_driver(self):
if self.driver_name.lower() == 'chrome':
return self.__get_chrome_driver()
elif self.driver_name.lower() == 'firefox':
return self.__get_firefox_driver()
elif self.driver_name.lower() == 'edge':
return self.__get_edge_driver()
def __get_chrome_driver(self):
# 先封装简易代码
# 加入系统环境判断
if system_driver.lower() == "darwin":
"""如果是mac系统执行这个驱动"""
chrome_path = os.path.join(current_path, '..', 'webdriver', 'chrome', 'chromedriver.exe')
driver = webdriver.Chrome(executable_path=chrome_path)
return driver
else:
chrome_path = os.path.join(current_path, '..', 'webdriver', 'chrome', 'chromedriver93.exe')
driver = webdriver.Chrome(executable_path=chrome_path)
return driver
def __get_firefox_driver(self):
if system_driver.lower() == "darwin":
firefox_path = os.path.join(current_path, '..', 'webdriver', 'firefox', 'geckodriver')
driver = webdriver.Firefox(executable_path=firefox_path)
return driver
else:
firefox_path = os.path.join(current_path, '..', 'webdriver', 'firefox', 'geckodriver.exe')
driver = webdriver.Firefox(executable_path=firefox_path)
return driver
def __get_edge_driver(self):
"""
驱动下载地址:https://developer.microsoft.com/zh-cn/microsoft-edge/tools/webdriver/
:return:
"""
edge_path = os.path.join(current_path, '..', 'webdriver', 'edge', 'msedgedriver.exe')
driver = webdriver.Edge(executable_path=edge_path)
return driver
if __name__ == '__main__':
driver = BrowserUtils().get_driver()
driver.get("https://www.baidu.com")
去除浏览器控制白条
# -*- coding: utf-8 -*-
# @Time : 2022/1/4 19:44
# @Author : Limusen
# @File : browser_utils
# 封装驱动类
import os
import sys
import warnings
from selenium import webdriver
from common.config_utils import local_config
from selenium.webdriver.chrome.options import Options
current_path = os.path.dirname(os.path.abspath(__file__))
system_driver = sys.platform
class BrowserUtils:
def __init__(self):
# 去除控制台警告
warnings.filterwarnings("ignore", category=DeprecationWarning)
self.driver_name = local_config.driver_name
def get_driver(self):
if self.driver_name.lower() == 'chrome':
return self.__get_chrome_driver()
elif self.driver_name.lower() == 'firefox':
return self.__get_firefox_driver()
elif self.driver_name.lower() == 'edge':
return self.__get_edge_driver()
def __get_chrome_driver(self):
# 先封装简易代码
# 加入系统环境判断
chrome_options = Options()
chrome_options.add_argument('--disable-gpu') # 谷歌文档提到需要加上这个属性来规避bug
chrome_options.add_argument('lang=zh_CN.UTF-8') # 设置默认编码为utf-8
chrome_options.add_experimental_option('useAutomationExtension', False) # 取消chrome受自动控制提示
chrome_options.add_experimental_option("excludeSwitches", ['enable-automation']) # 取消chrome受自动控制提示
if system_driver.lower() == "darwin":
"""如果是mac系统执行这个驱动"""
chrome_path = os.path.join(current_path, '..', 'webdriver', 'chrome', 'chromedriver.exe')
driver = webdriver.Chrome(executable_path=chrome_path, options=chrome_options)
return driver
else:
chrome_path = os.path.join(current_path, '..', 'webdriver', 'chrome', 'chromedriver93.exe')
driver = webdriver.Chrome(executable_path=chrome_path, options=chrome_options)
return driver
def __get_firefox_driver(self):
if system_driver.lower() == "darwin":
firefox_path = os.path.join(current_path, '..', 'webdriver', 'firefox', 'geckodriver')
driver = webdriver.Firefox(executable_path=firefox_path)
return driver
else:
firefox_path = os.path.join(current_path, '..', 'webdriver', 'firefox', 'geckodriver.exe')
driver = webdriver.Firefox(executable_path=firefox_path)
return driver
def __get_edge_driver(self):
"""
驱动下载地址:https://developer.microsoft.com/zh-cn/microsoft-edge/tools/webdriver/
:return:
"""
edge_path = os.path.join(current_path, '..', 'webdriver', 'edge', 'msedgedriver.exe')
driver = webdriver.Edge(executable_path=edge_path)
return driver
if __name__ == '__main__':
driver = BrowserUtils().get_driver()
driver.get("https://www.baidu.com")
到此 封装驱动类就结束了 小伙伴可以在不同的系统尝试一下
总结
本章节主要是讲述了一下ini配置文件,可以通过读取配置文件,来设置一些默认值,方便数据读取,封装驱动类方便其他模块调用,以及区分不同系统版本调用不同的driver驱动;
代码
地址 : https://gitee.com/todayisgoodday/PythonSelenium
博客园地址
https://www.cnblogs.com/yushengaqingzhijiao/category/2000515.html