webUI自动化(六)webUI脚本优化

webUI自动化(六)webUI脚本优化

一、整理excel表
  1. 添加【配置项】页,用于存放公共url,用例表中采用拼接方法打开url
  2. 【配置项】页添加无头模式和界面模式配置
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述
二、yaml配置文件操作
  1. 添加config.yaml配置文件
    在这里插入图片描述
  2. 添加yaml工具类
import yaml

def yaml_read(file_path):
    """read"""
    with open(file_path,'r',encoding='utf-8') as f:
        x = yaml.load(f,Loader=yaml.FullLoader)
    return x

def yaml_a_write(file_path,data):
    """追加写入"""
    f = open(file_path,'a',encoding='utf-8')
    yaml.dump(data,f,allow_unicode=True)
    f.close()

def yaml_w_write(file_path,data):
    """覆盖写入"""
    f = open(file_path,'w',encoding='gbk')
    yaml.dump(data,f,allow_unicode=True)
    f.close()

def yaml_dict_update(file_path,dict_data):
    """对yaml(only for dict)进行更新"""
    try:
        x = yaml_read(file_path)
        if not x:
            x = dict()
        x.update(dict_data)
        yaml_w_write(file_path,x)
    except:
        print(f'{file_path}<<<<<{dict_data}更新失败!!!')
        raise

if __name__ == '__main__':
    res = yaml_read(r"E:\pythonProject\ZrlogWebUI\config\config.yaml")
    print(res)

  1. 把excel【配置项】页读取,并存入yaml文件
class Script:
    def __init__(self, excel_path, config_path):
        # 实例化Base
        self.b = Base(config_path)  # 类属性
        # 获取excel对象,得到数据
        self.excel_obj = openpyxl.load_workbook(excel_path)  # 类属性
        #把配置文件读取并存入config.yaml
        config_sheet_values = self.excel_obj['配置项'].values
        config_dict = dict()
        for config_data in config_sheet_values:
            if config_data[0] != '编号':
                config_dict[config_data[1]] = config_data[2]    # config_data[1]为key,config_data[2]为值
        yaml_w_write(config_path,config_dict)       #写入配置信息到config.yaml

三、url拼接
    def open(self, data_dict):
        """打开网址"""
        base_url = self.config_dict[data_dict['locate_by']]
        self.driver.get(urljoin(base_url,data_dict['txt']))
四、增加无头模式判断
class Base:
    def __init__(self,config_file_path):
        self.config_dict = yaml_read(config_file_path)
        option = chrome_options()
        if int(self.config_dict['headless']) == 1:
            option.add_argument("--headless")
        self.driver = webdriver.Chrome(chrome_options=chrome_options())
        self.driver.implicitly_wait(5)  # 隐式等待5秒

五、异常捕获
    def run(self, sheet_name):  # 类方法
        """运行某sheet页的脚本"""
        # 获取sheet页的值
        self.sheet_obj = self.excel_obj[sheet_name]  # 获取sheet页对象
        values = self.sheet_obj.values  # 获取sheet页值

        for value in values:
            # for循环每一行并执行
            data_dict = dict()  # 用一个字典来接收当前行的值
            if value[0] != '编号' and int(value[1]) == 1:
                data_dict['no'] = value[0]
                data_dict['step_name'] = value[2]
                data_dict['kw'] = value[3]
                data_dict['locate_by'] = value[4]
                data_dict['locate_value'] = value[5]
                data_dict['txt'] = value[6]
                data_dict['note'] = value[7]
                data_dict['except'] = value[8]

                try:
                    # 执行用例
                    # 获取属性:getattr(对象,属性名称/方法名)(参数)
                    # getattr(对象,属性名称/方法名)(参数)传入参数 data_dict 原因:base工具类中的各个方法有不同长度的参数,
                    # 有些3个如:input(self,ele_type,ele_value,txt);有些2个如:excel_read(excel_path,sheet_name),有些没有如:switch_to_windows(self)
                    # 长度不一,因此传入 data_dict,进行传参,让各个参数优化为字典传参,优化base工具类
                    getattr(self.b, data_dict['kw'])(data_dict)
                    print(data_dict['step_name'],'执行成功!')
                except Exception as e:
                    print(data_dict['step_name'],'执行失败!',e)
                    raise
六、webUI脚本优化完整代码
  1. 目录结构
    在这里插入图片描述
  2. chrome_options.py
from selenium import webdriver

def chrome_options():
    options = webdriver.ChromeOptions()
    options.add_experimental_option('excludeSwitches',['enable-automation'])    #去掉默认的自动化提示
    options.add_argument('start-maximized')     #窗口最大化
    prefs = {"credentials_enable_service": False, "pofile.password_manager_enable": False}
    options.add_experimental_option("prefs", prefs)         #去掉密码管理弹窗
    options.add_argument("--no-sandbox")        #关闭沙盒模式
    # options.add_argument("--headless")      #无头模式,无界面运行
    options.add_argument('--kiosk-printing')        #弹出打印窗口时,自动按下打印按钮

    return options
  1. yaml_tools.py
import yaml

def yaml_read(file_path):
    """read"""
    with open(file_path,'r',encoding='utf-8') as f:
        x = yaml.load(f,Loader=yaml.FullLoader)
    return x

def yaml_a_write(file_path,data):
    """追加写入"""
    f = open(file_path,'a',encoding='utf-8')
    yaml.dump(data,f,allow_unicode=True)
    f.close()

def yaml_w_write(file_path,data):
    """覆盖写入"""
    f = open(file_path,'w',encoding='gbk')
    yaml.dump(data,f,allow_unicode=True)
    f.close()

def yaml_dict_update(file_path,dict_data):
    """对yaml(only for dict)进行更新"""
    try:
        x = yaml_read(file_path)
        if not x:
            x = dict()
        x.update(dict_data)
        yaml_w_write(file_path,x)
    except:
        print(f'{file_path}<<<<<{dict_data}更新失败!!!')
        raise

if __name__ == '__main__':
    res = yaml_read(r"E:\pythonProject\ZrlogWebUI\config\config.yaml")
    print(res)

  1. base_06_webUI脚本优化.py
from time import sleep
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait

from base.chrome_options import chrome_options
from base.yaml_tools import yaml_read
from urllib.parse import urljoin


class Base:
    def __init__(self,config_file_path):
        self.config_dict = yaml_read(config_file_path)
        option = chrome_options()
        if int(self.config_dict['headless']) == 1:
            option.add_argument("--headless")
        self.driver = webdriver.Chrome(chrome_options=chrome_options())
        self.driver.implicitly_wait(5)  # 隐式等待5秒


    def open(self, data_dict):
        """打开网址"""
        base_url = self.config_dict[data_dict['locate_by']]
        self.driver.get(urljoin(base_url,data_dict['txt']))

    def locate(self, data_dict):
        """定位,应用显式等待"""
        """
        WebDriverWait(driver,timeout,poll_frequency,ignored_exceptions)
            driver:浏览器驱动
            timeout:最长超时时间,默认以秒为单位。
            poll_frequency:检测的间隔步长,默认为0.5s。即每0.5s询问一次,元素是否找到。
            ignored_exceptions:超时后的抛出的异常信息,默认抛出NoSuchElementExeception异常。
        """
        try:
            ele = WebDriverWait(self.driver, 6, 0.5).until(
                lambda s: s.find_element(data_dict['locate_by'], data_dict['locate_value']))  # 显式等待
            # ele = self.driver.find_element(ele_type,ele_value)
            return ele
        except:
            print("定位失败")
            raise

    def input(self, data_dict):
        """输入"""
        self.locate(data_dict).send_keys(data_dict['txt'])
        # self.driver.find_element(ele_type,ele_value).send_keys(txt)

    def click(self, data_dict):
        """单击"""
        self.locate(data_dict).click()
        # self.driver.find_element(ele_type,ele_value).click()

    def max_window(self, data_dict):
        """窗口最大化"""
        self.driver.maximize_window()

    def switch_to_iframe(self, data_dict):
        """切换到iframe"""
        self.driver.switch_to.frame(data_dict['txt'])

    def switch_to_windows(self, data_dict):
        """切换新窗口"""
        windows = self.driver.window_handles
        self.driver.switch_to.window(windows[int(data_dict['txt'])])  # 指定切换哪一页面,-1为最新页面

    def assert_locate(self, data_dict):
        """断言"""
        assert self.locate(data_dict) is not None, '断言失败'
        print('断言成功!')

    def wait(self, data_dict):
        """固定等待"""
        sleep(int(data_dict['txt']))

    def quit(self, data_dict):
        """退出浏览器"""
        self.driver.quit()

  1. main06_webUI脚本优化.py
import openpyxl

from base.base_06_webUI脚本优化 import Base
from base.yaml_tools import *


class Script:
    def __init__(self, excel_path, config_path):
        # 实例化Base
        self.b = Base(config_path)  # 类属性
        # 获取excel对象,得到数据
        self.excel_obj = openpyxl.load_workbook(excel_path)  # 类属性
        #把配置文件读取并存入config.yaml
        config_sheet_values = self.excel_obj['配置项'].values
        config_dict = dict()
        for config_data in config_sheet_values:
            if config_data[0] != '编号':
                config_dict[config_data[1]] = config_data[2]    # config_data[1]为key,config_data[2]为值
        yaml_w_write(config_path,config_dict)       #写入配置信息到config.yaml


    def run(self, sheet_name):  # 类方法
        """运行某sheet页的脚本"""
        # 获取sheet页的值
        self.sheet_obj = self.excel_obj[sheet_name]  # 获取sheet页对象
        values = self.sheet_obj.values  # 获取sheet页值

        for value in values:
            # for循环每一行并执行
            data_dict = dict()  # 用一个字典来接收当前行的值
            if value[0] != '编号' and int(value[1]) == 1:
                data_dict['no'] = value[0]
                data_dict['step_name'] = value[2]
                data_dict['kw'] = value[3]
                data_dict['locate_by'] = value[4]
                data_dict['locate_value'] = value[5]
                data_dict['txt'] = value[6]
                data_dict['note'] = value[7]
                data_dict['except'] = value[8]

                try:
                    # 执行用例
                    # 获取属性:getattr(对象,属性名称/方法名)(参数)
                    # getattr(对象,属性名称/方法名)(参数)传入参数 data_dict 原因:base工具类中的各个方法有不同长度的参数,
                    # 有些3个如:input(self,ele_type,ele_value,txt);有些2个如:excel_read(excel_path,sheet_name),有些没有如:switch_to_windows(self)
                    # 长度不一,因此传入 data_dict,进行传参,让各个参数优化为字典传参,优化base工具类
                    getattr(self.b, data_dict['kw'])(data_dict)
                    print(data_dict['step_name'],'执行成功!')
                except Exception as e:
                    print(data_dict['step_name'],'执行失败!',e)
                    raise


    def quit(self):  # 类方法
        # 退出浏览器和excel对象
        self.b.wait({'txt': '5'})
        self.excel_obj.close()
        self.quit({})


if __name__ == '__main__':
    excel_path = "./data/data.xlsx"
    config_path = "./config/config.yaml"
    s = Script(excel_path, config_path)
    try:
        s.run("bilibili")
    finally:
        s.quit()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值