首页 > 其他分享 >定位元素封装find_element(增加显性等待等)

定位元素封装find_element(增加显性等待等)

时间:2023-10-13 20:45:22浏览次数:28  
标签:封装 get self value element step selector find

 

封装

# find_elementUtil.py
import os
import time
from selenium.webdriver.support import expected_conditions as EC
from appium.webdriver.common.appiumby import AppiumBy

from selenium.webdriver.support.wait import WebDriverWait

# from base import driver_configure
# from selenium.webdriver.support.wait import WebDriverWait
# from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException


class ElementClass:
    def __init__(self, driver):  # 构造函数。实例化每个页面的时候,都可以获取到java对象
        self.driver = driver

    def find_element(self, location_type, locator_expression):  # 元素定位
        """
        重写find_element方法,显式等待
        """
        try:
            element = WebDriverWait(self.driver, 10, 1).until(
                EC.visibility_of_element_located((getattr(AppiumBy, location_type), locator_expression)))
            return element
        except NoSuchElementException as msg:
            print(u"查找元素异常: %s" % msg)
            # self.driver.back()
            # raise msg  # 抛出异常
            return False

    def is_element(self, location_type, locator_expression):  # 判断元素是否存在
        e = self.driver.find_element(location_type, locator_expression) == []
        if e:
            return False
        else:
            return True

    def send_keys(self, location_type, locator_expression, value):
        try:
            self.find_element(location_type, locator_expression).clear()
            self.find_element(location_type, locator_expression).send_keys(value)
        except AttributeError as e:
            raise e

    def element_click(self, location_type, locator_expression):  # 单击操作
        try:
            self.find_element(location_type, locator_expression).click()
        except AttributeError as e:
            raise e

    def get_attributes(self, location_type, locator_expression, text_value):  # 获取值
        try:
            attr_ = self.find_element(location_type, locator_expression).get_attribute(text_value)
            return attr_
        except AttributeError as e:
            raise e

    # 保存图片
    def get_windows_img(self):
        """
        在这里我们把file_path这个参数写死,直接保存到我们项目根目录的一个文件夹'Screenshots'下
        """
        # 获取到当前文件的目录,并检查是否有screenshots文件夹,如果不存在则自动新建screenshots文件
        file_path = os.path.dirname(os.path.abspath("."))+'/screenshots/'
        if not os.path.exists(file_path):
            os.makedirs(file_path)

        rq = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))
        screen_name = file_path+rq+'.png'
        try:
            self.driver.get_screenshot_as_file(screen_name)
        except NameError as e:
            print(e)
            self.get_windows_img()

(测试用例读取写入excel)appium+pytest数据驱动  的action文件部分重新如下:(excel文件模式也有所改变)

 

# ren_excel_step.py
from util.excel_readUtil import HandleExcel
# from appium.webdriver import WebElement
from config.driver_configure import DriverClinet
from util.assertUtil import AssertUtil
import allure
from util.find_elementUtil import ElementClass
# from util.loggerUtil import Logger


class Context:
    pass


def step_case(fimename, sheetname):
    driver = DriverClinet().get_driver()
    class_driver = ElementClass(driver)
    case = HandleExcel(fimename, sheetname).get_cases()
    # 遍历测试用例下的具体步骤
    for step in case:
        action_ = step.get('action', None)  # 如果用step['action'],当step没有action会抛异常,action指操作有定位元素、点击、输入等操作
        desc_d = step.get('description', None)  # 获取描述内容
        ele_ = step.get('element_operator', None)
        # find_ = step.get('find', None)  # 定位元素,是find_element、还是find_elements
        selector_ = step.get('selector', None)  # 定位元素的类型
        selector_value_ = step.get('selector_value', None)  # 定位元素的值
        save_val_ = step.get('save_val', None)  # 将操作的结果保存的对象名
        # operate_obj_ = step.get('operate_object', None)  # 对哪个对象进行操作
        inputtext_ = step.get('inputtext', None)  # 输入操作的驶入内容
        attribute_value_ = step.get('attribute_value', None)  # 获取对象什么属性
        if action_ == 'desc':
            allure.dynamic.title(desc_d)
        if action_ == 'click':
            if ele_:
                if selector_ and selector_value_:
                    class_driver.__getattribute__(ele_)(selector_, selector_value_)
                else:
                    raise ValueError('在用例文件{}行缺少定义selector_或selector_value_的值'.format(case.index(step)))
            else:
                raise ValueError('在用例文件{}行缺少定义ele_的值'.format(case.index(step)))
        if action_ == 'send_keys':
            if selector_ and selector_value_:
                if inputtext_:
                    class_driver.__getattribute__(ele_)(selector_, selector_value_, inputtext_)
                else:
                    raise ValueError('在用例文件{}行缺少定义inputtext_的值'.format(case.index(step)))
            else:
                raise ValueError('在用例文件{}行缺少定义selector_或selector_value_的值'.format(case.index(step)))
        if action_ == 'get_attribute':
            if ele_ == 'get_attributes':
                if attribute_value_:
                    setattr(Context, save_val_, class_driver.__getattribute__(ele_)(selector_, selector_value_, attribute_value_))
                    # class_driver.__getattribute__(ele_)(selector_, selector_value_, attribute_value_)
                else:
                    raise ValueError('在用例文件{}行缺少定义attribute_value_的值'.format(case.index(step)))
            else:
                raise ValueError('在用例文件{}行缺少定义ele_的值'.format(case.index(step)))
        if action_ == 'assert':
            step_ = step.get('step_name', None)  # 获取步骤名
            assert_type_ = step.get('assert_type', None)
            assert_value_ = step.get('assert_value', None)
            expect_value_ = step.get('expect_value', None)
            if step_:  # 判断步骤名称,设置为必填的情况,要不然无法执行assert指令,如果不需要allure报告的话,该判断可以不用
                with allure.step(step_):
                    if assert_value_:
                        if str(assert_value_).find('$') == 0:
                            # 需要取变量
                            assert_value_ = getattr(Context, str(assert_value_).lstrip('$'))
                        if str(expect_value_).find('$') == 0:
                            expect_value_ = getattr(Context, str(expect_value_).lstrip('$'))
                    if assert_type_ and assert_value_:
                        AssertUtil(assert_type_, getattr(Context, assert_value_), expect_value_)
                    else:
                        raise ValueError('在用例文件{}行缺少定义assert_type_的值'.format(case.index(step)))
            else:
                raise ValueError('在用例文件{}行缺少定义step_的值'.format(case.index(step)))

运行后正常

标签:封装,get,self,value,element,step,selector,find
From: https://www.cnblogs.com/may18/p/17763101.html

相关文章

  • 封装Axios的POST和GET
    对Axios的POST和GET请求的封装POST请求的两种形式。参数JSON格式/***传递json数据,在请求报文中是json格式*@paramurl*@paramparams*@returns{AxiosPromise}*/functiondoPostJson(url,params){returnaxios({url:url,method:'pos......
  • /usr/bin/ld: cannot find -lxxx 的解决方法总结
    问题原因:1、系统没有按照相应的lib2、相对应的lib版本不对3、lib的symboliclink不对,没有连接到正确的函数库文件(so)解决:对于1,2种情况:apt-getinstalllibxxx-dev对于3中情况:可以先用locate和find找到指定的lib文件,查看链接文件是否正确的指向了我们希望的lib,如果不是,......
  • elementui表格复杂操作
    1.elementui表格最后一行加粗显示表格table加以下属性:cell-style="cellStyleModify"methods方法实现:cellStyleModify({row,column,rowIndex,columnIndex}){letfontStyle=null;if(row.ggmc.includes('合计')){fontStyle='font-wei......
  • element表格的表头添加*星号
    vue怎么实现element表格里表头信息提示功能?第一、给el-table添加:header-cell-class-name<el-table:header-cell-class-name="func"></el-table>第二、在vue的methods中编写方法//给头部添加星星func(obj){letlist=['表头1','表头2','表头3','......
  • element-ui 解决 table 里包含表单验证
    实际项目中的场景,需要在table里做表单的验证,如图效果: 其实问题关键就在于如何给el-form-item动态绑定prop      :prop="'tableData.'+scope.$index+'.字段名'"   ......
  • js封装获取当前周数据
     /**@Author:张大碗[email protected]*@Date:2023-09-2017:36:15*@LastEditors:张大碗[email protected]*@LastEditTime:2023-10-0811:04:08*@FilePath:\vue-vant2-template-master\vue-vant2-template-master\src\utils\week.j......
  • Blazor Server App Cannot find the fallback endpoint specified by route values
    github官方issues中提到的解决方案,CreateBuilder时指定项目绝对路径可以解决。1//指定项目路径,也可以用Assembly.GetCallingAssembly获取2conststringContentRootPath=@"C:\Users\BlazorServer";//项目的路径3conststringApplicationName=nameof(BlazorServer);......
  • 网络基础-OSI七层vsTCP/UDP四层 五层 数据封装
    1.0网络基础1.1网络是什么?网络是信息传输、接收、共享的虚拟平台,通过它把各个点、面、体的信息联系到一起,从而实现这些资源的共享网络分类:局域网,城域网,广域网1.2数据通信方式单播:一对一组播:一对多广播:一对所有2.0OIS七层模型vsTCP/IP四层五层模型 2.1分层思想①......
  • ElementPlus el-select自动获取焦点问题
    原因:以下el-select主要代码是在document页面上,而el-dialog在点击关闭按钮时,从而关闭el-dialog后,会自动使el-select组件获取到焦点。<el-popover:visible="data.tipVisible"ref="popover"placement="left-start":title="title&q......
  • ASEMI整流桥GBU810参数,GBU810封装
    编辑-ZGBU810参数描述:型号:GBU810最大直流反向电压VR:1000V最大工作峰值反向电压VRWM:700V最大平均正向电流IF:8A非重复正向浪涌电流IFSM:200A操作和储存温度范围TJ,TSTG:-55to150℃正向电压VF:1.1V最大反向泄漏电流IRM:5uA每个元件的典型热阻RthJA:2.2℃/W GBU810封装规格:封装:GBU-4总长......