当前位置: 首页 > news >正文

Python+Selenium WebUI自动化框架 -- 基础操作封装

前言:

封装Selenium基本操作,让所有页面操作一键调用,让UI自动化框架脱离高成本、低效率时代,将用例的重用性贯彻到极致,让烦人的PO模型变得无所谓,让一个测试小白都能编写并实现自动化。

知识储备前提:熟练python语言理论与实际运用,熟悉selenium库与自动化测试环境配置。

browseroperator.py   浏览器操作
webdriveroperator.py     WEBd页操作

分层设计:基础目录,浏览器操作与WEB操作分开。

一、browseroperator.py 的代码如下:

1、初始化函数def __init__(self),初始化浏览相关参数

2、初始化浏览器方法def open_url(self, **kwargs),先判断使用哪种浏览器。

**kwargs是不定长参数,dict格式,参数只需要传 url='www.baidu.com' ,方法调用只用 opr.open_url(url='www.baidu.com'),打开了浏览器,他会返回webdriver的句柄,调用处接收到全流程操作网站元素。

暂时还未封装IE 、火狐,留给各位朋友们实现吧,让我们一起学习

现在我也找了很多测试的朋友,做了一个分享技术的交流群,共享了很多我们收集的技术文档和视频教程。
如果你不想再体验自学时找不到资源,没人解答问题,坚持几天便放弃的感受
可以加入我们一起交流。而且还有很多在自动化,性能,安全,测试开发等等方面有一定建树的技术大牛
分享他们的经验,还会分享很多直播讲座和技术沙龙
可以免费学习!划重点!开源的!!!
qq群号:110685036【暗号:csdn999】

3、def close_browser(self, **kwargs)关闭浏览器,齐活,一并封装了

import os
import time
from selenium import webdriver
from common.getconf import Config
from common.getfiledir import BASEFACTORYDIRclass BrowserOperator(object):def __init__(self):self.conf = Config()self.driver_path = os.path.join(BASEFACTORYDIR, 'chromedriver.exe')def open_url(self, **kwargs):"""打开网页:param url::return: 返回 webdriver"""try:url = kwargs['locator']except KeyError:return False, '没有URL参数'try:type = self.conf.get('base', 'browser_type')   #从配置文件里取浏览器的类型if type == 'chrome':#处理chrom弹出的info# chrome_options = webdriver.ChromeOptions()# #option.add_argument('disable-infobars')# chrome_options.add_experimental_option("excludeSwitches", ['enable-automation'])# self.driver = webdriver.Chrome(options=chrome_options, executable_path=self.driver_path)self.driver = webdriver.Chrome(executable_path=self.driver_path)self.driver.maximize_window()self.driver.get(url)elif type == 'IE':print('IE 浏览器')else:print('火狐浏览器')except Exception as e:return False, ereturn True, self.driverdef close_browser(self, **kwargs):"""关闭浏览器:return:"""self.driver.quit()return True, '关闭浏览器成功'

二、webdriveroperator.py代码如下

1、def __init__(self, driver:Chrome),初始化浏览器返回的deriver句柄,

2、内容不一 一 介绍了,实现了所有页面的操作,定义成功与否判断、日志返回等细节。各位看官细细品尝,细节都在代码里,每个方法注释大体可以说明了这个方法意义,很容易看懂。

还有很多UI操作没有搬运上来,留给各位朋友们去实现吧,让我们一起学习

import os
import timefrom selenium.common.exceptions import NoSuchElementException
from selenium.webdriver import Chrome
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from common.getfiledir import SCREENSHOTDIRclass WebdriverOperator(object):def __init__(self, driver:Chrome):self.driver = driverdef get_screenshot_as_file(self):"""截屏保存:return:返回路径"""pic_name = str.split(str(time.time()), '.')[0] + str.split(str(time.time()), '.')[1] + '.png'screent_path = os.path.join(SCREENSHOTDIR, pic_name)self.driver.get_screenshot_as_file(screent_path)return screent_pathdef gotosleep(self, **kwargs):time.sleep(3)return True, '等待成功'def web_implicitly_wait(self, **kwargs):"""隐式等待:return:type  存时间"""try:s = kwargs['time']except KeyError:s = 10try:self.driver.implicitly_wait(s)except NoSuchElementException:return False, '隐式等待 页面元素未加载完成'return True, '隐式等待 元素加载完成'def web_element_wait(self, **kwargs):"""等待元素可见:return:"""try:type = kwargs['type']locator = kwargs['locator']except KeyError:return False, '未传需要等待元素的定位参数'try:s = kwargs['time']except KeyError:s = 30try:if type == 'id':WebDriverWait(self.driver, s, 0.5).until(EC.visibility_of_element_located((By.ID, locator)))elif type == 'name':WebDriverWait(self.driver, s, 0.5).until(EC.visibility_of_element_located((By.NAME, locator)))elif type == 'class':WebDriverWait(self.driver, s, 0.5).until(EC.visibility_of_element_located((By.CLASS_NAME, locator)))elif type == 'xpath':WebDriverWait(self.driver, s, 0.5).until(EC.visibility_of_element_located((By.XPATH, locator)))elif type == 'css':WebDriverWait(self.driver, s, 0.5).until(EC.visibility_of_element_located((By.CSS_SELECTOR, locator)))else:return False, '不能识别元素类型[' + type + ']'except NoSuchElementException:return False, '元素[' + locator + ']等待出现超时'return True, '元素[' + locator + ']等待出现成功'def find_element(self, type, locator, index = 0):"""定位元素:param type::param itor::param index::return:"""#isinstance(self.driver, selenium.webdriver.Chrome.)type = str.lower(type)try:if type == 'id':elem = self.driver.find_elements_by_id(locator)[index]elif type == 'name':elem = self.driver.find_elements_by_name(locator)[index]elif type == 'class':elem = self.driver.find_elements_by_class_name(locator)[index]elif type == 'xpath':elem = self.driver.find_elements_by_xpath(locator)[index]elif type == 'css':elem = self.driver.find_elements_by_css_selector(locator)[index]else:return False, '不能识别元素类型:[' + type + ']'except Exception:screenshot_path = self.get_screenshot_as_file()return False, '获取[' + type + ']元素[' + locator + ']失败,已截图[' + screenshot_path + '].'return True, elemdef element_click(self, **kwargs):"""点击:param kwargs::return:"""try:type = kwargs['type']locator = kwargs['locator']except KeyError:return False, '缺少传参'try:index = kwargs['index']except KeyError:index = 0_isOK, _strLOG = self.find_element(type, locator, index)if not _isOK:      #元素没找到,返回失败结果return _isOK, _strLOGelem = _strLOGtry:elem.click()except Exception:screenshot_path = self.get_screenshot_as_file()return False, '元素['+ locator +']点击失败,已截图[' + screenshot_path + '].'return True, '元素['+ locator +']点击成功'def element_input(self, **kwargs):"""输入:param kwargs::return:"""try:type = kwargs['type']locator = kwargs['locator']text = str(kwargs['input'])except KeyError:return False, '缺少传参'try:index = kwargs['index']except KeyError:index = 0_isOK, _strLOG = self.find_element(type, locator, index)if not _isOK:  # 元素没找到,返回失败结果return _isOK, _strLOGelem = _strLOG# if 'test' != elem.get_property('type'):     #校验元素是不是text输入框#     screenshot_path = self.get_screenshot_as_file()#     return False, '元素['+ itor +']不是输入框,输入失败,已截图[' + screenshot_path + '].'try:elem.send_keys(text)except Exception:screenshot_path = self.get_screenshot_as_file()return False, '元素['+ locator +']输入['+ text +']失败,已截图[' + screenshot_path + '].'return True, '元素['+ locator +']输入['+ text +']成功'

结语:封装了基础类,还得实现一个工厂,实现统一一个入口执行所有自动化

点赞关注~~~

http://www.lryc.cn/news/232507.html

相关文章:

  • PyCharm 【unsupported Python 3.1】
  • flutter TabBar指示器
  • PDF/X、PDF/A、PDF/E:有什么区别,为什么有这么多格式?
  • Microsoft发布了一份关于其产品安全修复的 11 月报告。
  • 12v24v60v高校同步降压转换芯片推荐
  • pip 问题
  • 云计算(一):弹性计算概述
  • Qt/C++ 获取QProcess启动的第三方软件的窗体标题
  • Borland编辑器DOS系统快捷键应用
  • KeyarchOS的CentOS迁移实践:使用操作系统迁移工具X2Keyarch V2.0
  • Golang抓包:实现网络数据包捕获与分析
  • 分类预测 | Matlab实现QPSO-SVM、PSO-SVM、SVM多特征分类预测对比
  • kubernetes部署jenkins
  • Node.js详解
  • v-html命令渲染的内容,使用scoped属性的情况下,样式不起作用
  • 浅谈vue2.0和vue3.0的区别
  • git clone报错SSL connect error
  • LeetCode(26)判断子序列【双指针】【简单】
  • 学习c#的第十五天
  • TrafficGPT: Viewing, Processing, and Interacting with Traffic Foundation Models
  • SPASS-参数估计与假设检验
  • 虚拟博物馆和纪念馆全景漫游
  • chrome 浏览器个别字体模糊不清
  • Resolume Arena 7.15.0(VJ音视频软件)
  • Java设计模式
  • 平均分(C++)
  • .NET8.0 AOT 经验分享 FreeSql/FreeRedis/FreeScheduler 均已通过测试
  • Django之模型层
  • 京东数据挖掘(京东运营数据分析):2023年宠物行业数据分析报告
  • 五分钟k8s实战-Istio 网关