千纸鹤

  博客园  ::  :: 新随笔  ::  ::  :: 管理
  5 随笔 :: 70 文章 :: 0 评论 :: 9301 阅读
《-----项目的目录结构-----》
  1、配置类:chrome_option(chrome_options.py)
  2、Excel管理数据类:data(excel_driver.xlsx)
  3、读取Excel数据类:excel_read(read.py)
  4、封装关键字类:web_keys(keys.py)
  5、程序主入口:main.py

一、配置类:chrome_option(chrome_options.py)
from time import sleep
from selenium import webdriver

class ChromeOptions:
def options(self):
# chrome浏览器的配置项,可以通过修改默认参数,改变默认启动的浏览器的形态
options = webdriver.ChromeOptions()
# 去掉默认的提示自动化信息:没啥用,一般没有什么影响。警告条可能会导致页面内容的遮挡或者挤压,影响自动化测试
options.add_experimental_option('excludeSwitches', ['enable-automation', 'enable-logging'])
# 读取本地缓存,实现一个有缓存的浏览器,这个指令执行前必须关闭所有本地的chrome浏览器
options.add_argument(r'--user-data-dir=C:\Users\xuzhu\AppData\Local\Google\Chrome\User Data')
# 去掉账号密码弹窗
prefs = {}
prefs["credentials-enable-service"] = False
prefs['profile.password_manager_enable'] = False
options.add_experimental_option("prefs", prefs)

return options

二、Excel管理数据类:data(excel_driver.xlsx)
   

三、读取Excel数据类:excel_read(read.py)
'''
基于Excel文件的内容去进行读取,并结合获取的数据进行自动化的测试执行
'''
import openpyxl
# 读取excel中的用例正文
from test008.test0082.test0082_01.web_keys.keys import Keys

def read(file):
excel = openpyxl.load_workbook(file)
for name in excel.sheetnames:
sheet = excel[name]
print('***********{}**************'.format(name))
for values in sheet.values:
# 如果第一个单元格是int类型,则表示进入了测试用例的正文
if type(values[0]) is int:
# print(values)
# 接收每一行操作行为对应的参数内容
data = {}
data['name'] = values[2]
data['value'] = values[3]
data['txt'] = values[4]
data['expect'] = values[6]

# print(data)
# 清除参数字典中为None的参数键值对
for key in list(data.keys()):
if data[key] is None:
del data[key]
print(data)

# 基于操作行为和对应参数来执行自动化操作
'''
用例的操作行为主要分为:
1. 实例化,通过一个操作行为实例化关键字驱动类对象
2. 常规操作,通过调用已实例化的对象,执行对应的函数。
3. 断言操作,判断预期与实际是否符合,将结果填入测试用例中。
'''
# 实例化关键字驱动
if values[1] == 'open_browser':
keys = Keys(**data)
# 等同于 Keys(txt='Chrome')
# 断言
elif 'assert' in values[1]:
status = getattr(keys, values[1])(**data)
# 基于断言结果True or False来进行写入的操作
if status:
sheet.cell(row=values[0] + 2, column=8).value = 'Pass'
else:
sheet.cell(row=values[0] + 2, column=8).value = 'Failed'
# 常规操作
else:
getattr(keys, values[1])(**data)
# 等同于 keys.input(name=xxx,value=xxx,txt=xxx)
excel.save(file)

四、封装关键字类:web_keys(keys.py)
# 自定义关键字驱动类
from time import sleep

from selenium import webdriver
from selenium.webdriver.common.by import By
from test008.test0082.test0082_01.chrome_option.chrome_options import ChromeOptions
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support.relative_locator import locate_with

def open_browser(type_):
if type_ == 'Chrome':
driver = webdriver.Chrome(options=ChromeOptions().options())
else:
try:
driver = getattr(webdriver, type_)()
except Exception as e:
print("Exception Information:" + str(e))
driver = webdriver.Chrome()
return driver

class Keys:
# (1)构造函数
def __init__(self, txt):
self.driver = open_browser(txt)
self.driver.implicitly_wait(10)

# (2)访问url
def open(self, txt):
self.driver.get(txt)

# (3)定位元素
def locate(self, name, value):
return self.driver.find_element(name, value)

# (4)点击操作
def click(self, name, value):
self.locate(name, value).click()

# (5)输入
def input(self, name, value, txt):
self.locate(name, value).send_keys(txt)

# (6)退出
def quit(self):
self.driver.quit()

# (7)显式等待
def web_el_wait(self, name, value):
return WebDriverWait(self.driver, 10, 0.5).until(
lambda el: self.locate(name, value), message='元素查找失败')

# (8)强制等待
def wait(self, txt):
sleep(txt)

# (9)切换Iframe
def switch_frame(self, value, name=None):
if name is None:
self.driver.switch_to.frame(value)
else:
self.driver.switch_to.frame(self.locate(name, value))

# (10)切换default窗体
def switch_default(self):
self.driver.switch_to.default_content()

# (11)相对定位器(相对比较复杂的定位器)
def locator_with(self, method, value, el_name, el_value, direction):
el = self.locate(el_name, el_value)
direction_dict = {
'left': 'to_left_of', # 左侧
'right': 'to_right_of', # 右侧
'above': 'above', # 上方
'below': 'below', # 下方
'near': 'near' # 靠近
}
if isinstance(method, str):
method_dict = {
"id": By.ID,
"xpath": By.XPATH,
"link text": By.LINK_TEXT,
"partial link text": By.PARTIAL_LINK_TEXT,
"name": By.NAME,
"tag name": By.TAG_NAME,
"class name": By.CLASS_NAME,
"css selector": By.CSS_SELECTOR
}
self.locate(locate_with(By.TAG_NAME, 'input').to_left_of(el))
return self.driver.find_element(getattr(
locate_with(method_dict.get(method), value), direction_dict.get(direction))(el))

# (12)句柄的切换(考虑不同场景的不同切换)
def switch_handle(self, close=False, index=1):
handles = self.driver.window_handles
if close:
self.driver.close()
self.driver.switch_to.window(handles[index])

# (13)断言文本信息:可以捕获异常进行处理,也可以不捕获,因为报错就相当于断言失败。
def assert_text(self, name, value, expect):
try:
reality = self.locate(name, value).text
assert expect == reality, '断言失败,实际结果为:{}'.format(reality)
return True
except Exception as e:
print('断言失败信息:' + str(e))
return False

五、程序主入口:main.py
'''
程序主入口
'''
from test008.test0082.test0082_01.excel_read import read

if __name__ == '__main__':
read.read('./data/excel_driver.xlsx')
posted on   隆江猪脚饭  阅读(102)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示