Exemplo n.º 1
0
 def wait_ele_visible(self, locator, doc="", times=30, poll_frequency=0.5):
     """
     :param locator: 元素定位表达式
     :param doc: 操作的模块名_页面名_操作名(用于异常时截图存储的截图图片名称)
     :param times:等待时间
     :param poll_frequency:轮询间隔时间
     :return:
     """
     MyLog().info('等待元素{}可见'.format(locator))
     try:
         #开始等待时间
         start_time = datetime.now()
         # MyLog().info("等待开始时间{}:".format(start_time))
         WebDriverWait(self.driver, times, poll_frequency).until(
             EC.visibility_of_element_located(locator))
         #结束等待时间
         end_time = datetime.now()
         #求等待的差值,写在日志中,等待了多久
         wait_time = (end_time - start_time).seconds
         MyLog().info("wait_time:{}".format(wait_time))
         MyLog().info("等待结束,等待时长为{}秒".format(wait_time))
     except:
         MyLog().info('等待元素失败!!!!!!!!!!!!!')
         #截图
         self.save_screenshot(doc)
         raise
Exemplo n.º 2
0
 def save_screenshot(self, doc):
     MyLog().info("截取屏幕")
     #图片名称:模块名_页面名_操作名_时间.png
     file_name = screenshot_path + '\\' + GetTime().get_time_by_second(
     ) + '_' + doc + ".png"
     self.driver.save_screenshot(file_name)
     MyLog().info("截取屏幕完成,存放地址在{}".format(file_name))
Exemplo n.º 3
0
 def click_elements(self, locator, index, doc=''):
     eles = self.get_elements(locator, doc)
     try:
         eles[index].click()
         MyLog().info('点击元素{}'.format(locator))
     except:
         MyLog().info('点击元素失败!!!!!!!!!!!!!')
         self.save_screenshot(doc)
         raise
Exemplo n.º 4
0
 def clear_loc_text(self, locator, doc=""):
     ele = self.get_element(locator, doc)
     MyLog().info('清除元素{}的文本内容'.format(locator))
     try:
         ele.clear()
     except:
         MyLog().info('清除元素文本失败!!!!!!!!!!!!!')
         self.save_screenshot(doc)
         raise
Exemplo n.º 5
0
 def click_element(self, locator, doc=""):
     #先找到元素
     ele = self.get_element(locator, doc)
     MyLog().info('点击元素{}'.format(locator))
     try:
         ele.click()
     except:
         MyLog().info('点击元素失败!!!!!!!!!!!!!')
         self.save_screenshot(doc)
         raise
Exemplo n.º 6
0
 def get_text(self, locator, doc=""):
     # 先找到元素
     ele = self.get_element(locator, doc)
     MyLog().info('获取元素{}的文本内容'.format(locator))
     try:
         return ele.text
     except:
         MyLog().info('获取元素文本失败!!!!!!!!!!!!!')
         self.save_screenshot(doc)
         raise
Exemplo n.º 7
0
 def get_ele_aattribute(self, locator, attr, doc=""):
     # 先找到元素
     ele = self.get_element(locator, doc)
     MyLog().info('获取元素{}的属性'.format(locator))
     try:
         return ele.get_attribute(attr)
     except:
         MyLog.info('获取元素属性失败!!!!!!!!!!!!!')
         self.save_screenshot(doc)
         raise
Exemplo n.º 8
0
 def dismiss_alert(self, times=30, poll_frequency=0.5, doc=''):
     try:
         WebDriverWait(self.driver, times,
                       poll_frequency).until(EC.alert_is_present())
         alert = self.driver.switch_to_alert()
         alert.dismiss()
     except:
         MyLog.info('弹窗不存在!!!!!!!!!!!!!')
         self.save_screenshot(doc)
         raise
Exemplo n.º 9
0
 def get_elements(self, locator, doc=""):
     MyLog().info('查找元素{}'.format(locator))
     try:
         eles = self.driver.find_elements(*locator)
         return eles
     except:
         MyLog().info('查找元素失败!!!!!!!!!!!!!')
         # 截图
         self.save_screenshot(doc)
         raise
Exemplo n.º 10
0
 def input_text(self, locator, text, doc=""):
     # 先找到元素
     ele = self.get_element(locator, doc)
     MyLog().info('向元素{}输入文本{}'.format(locator, text))
     try:
         ele.send_keys(text)
     except:
         MyLog().info('输入文本失败!!!!!!!!!!!!!')
         self.save_screenshot(doc)
         raise
Exemplo n.º 11
0
 def get_toastMsg(self, str):
     #1、xpath表达式,文本匹配
     loc = '//*[contains(@test,"{}")]'.format(str)
     #等待室等待元素存在,不能用等待元素可见
     try:
         WebDriverWait(self.driver, 10, 0.01).until(
             EC.visibility_of_element_located((MobileBy.XPATH, loc)))
         return self.driver.find_element_by_xpath(loc).text
     except:
         MyLog.info('没有找到匹配的toast!!!')
         raise
Exemplo n.º 12
0
 def get_element(self, locator, doc=""):
     MyLog().info('查找元素{}'.format(locator))
     try:
         # self.wait_ele_visible(*locator)
         ele = self.driver.find_element(*locator)
         #返回元素对象,以便进行后续操作
         return ele
     except:
         MyLog().info('查找元素失败!!!!!!!!!!!!!')
         # 截图
         self.save_screenshot(doc)
         raise
Exemplo n.º 13
0
 def goto_hall_gateway(self):
     try:
         # 点击设备管理一级菜单
         self.click_element(loc.hall_equipment)
         # 点击网络通道管理菜单
         self.click_element(loc.hall_gateway)
         # 切换iframe到新打开的tab里面
         self.switch_iframe_to_new_tab()
         MyLog().info('已进入网络通道管理界面!!!')
         from PageObjects.HallEquipmentPages.hall_gateway_page import HallGatewayPage
         return HallGatewayPage()
     except:
         MyLog().error('进入网络通道管理界面失败!!!')
Exemplo n.º 14
0
 def goto_hall_equipment(self):
     try:
         # 关闭已默认打开的tab
         self.close_tab_already_opened()
         # 点击设备管理一级菜单
         self.click_element(loc.hall_equipment)
         # 点击设备管理二级菜单
         self.click_element(loc.hall_equipment_2)
         self.switch_iframe_to_new_tab()
         MyLog().info('已进入设备管理界面!!!')
         from PageObjects.HallEquipmentPages.hall_equipment_page import HallEquimentPage
         return HallEquimentPage()
     except:
         MyLog().error('进入设备管理界面失败!!!')
Exemplo n.º 15
0
    def confirm_and_swichTo_usedCar(self):
        for i in range(3):
            #点击一下屏幕上方,以防有页面弹窗导致无法找到以下元素,点击屏幕上方可以关闭弹窗。
            size = self.get_size()
            x = int(size["width"] * 0.5)
            y = int(size["height"] * 0.1)
            self.driver.tap([(x, y)], 100)
            #1,如果找到元素“提交线索”,说明在二手车页面
            if self.is_ele_visible(idx_loc.link_submit_clues):
                print("当前在二手车首页,无需切换")
                break
            #2,如果未找到元素“提交线索”,找是否有关闭页面的“X”号,关闭页面回到工作台,再切换至二手车首页
            elif self.is_ele_visible(com_loc.close_window):
                self.click_element(com_loc.close_window)
                self.switchTo_usedCar()
                print("当前在页面有“X”号")
                continue
            #3,查找是否有“工作台”元素,有的话可以切换到二手车首页
            elif self.is_ele_visible(com_loc.tab_workSpace):
                self.switchTo_usedCar()
                continue
            #4,以上都没找到
            else:
                MyLog().info("当前页面无法切换至二手车首页!")
                print("当前页面无法切换至工作台")

                break
Exemplo n.º 16
0
 def get_alert_text(self, times=30, poll_frequency=0.5, doc=''):
     #等待弹窗存在
     try:
         WebDriverWait(self.driver, times,
                       poll_frequency).until(EC.alert_is_present())
         alert = self.driver.switch_to_alert()
         MyLog().info('弹窗存在,获取弹框的文本内容')
         try:
             return alert.text
         except:
             MyLog.info('获取弹框的文本内容失败!!!!!!!!!!!!!')
             self.save_screenshot(doc)
             raise
     except:
         MyLog.info('弹窗不存在!!!!!!!!!!!!!')
         self.save_screenshot(doc)
         raise
Exemplo n.º 17
0
 def delete_datas_from_table_with_sql(self, sql):  # 用来删除指定表中的所有数据
     '''
     :param table_name: 数据库中表的名字
     :return:
     '''
     try:
         db_config = eval(ReadConfig().get_config_data(
             config_path, 'DB', 'db_config'))
         cnn = mysql.connector.connect(**db_config)  # 建立数据库连接
         cursor = cnn.cursor()  # 游标cursor
         cursor.execute(sql)  # 执行语句
         cnn.commit()  # 提交
         cursor.close()  # 关闭游标
         cnn.close()  # 关闭连接
         MyLog().info('执行数据库语句--》{}《--成功!!!'.format(sql))
     except:
         MyLog().error('执行数据库语句--》{}《--失败!!!'.format(sql))
Exemplo n.º 18
0
 def is_ele_visible(self, locator, doc="", times=30, poll_frequency=0.5):
     """
     :param locator: 元素定位表达式
     :param doc: 操作的模块名_页面名_操作名(用于异常时截图存储的截图图片名称)
     :param times:等待时间
     :param poll_frequency:轮询间隔时间
     :return:
     """
     MyLog().info('等待元素{}可见'.format(locator))
     try:
         WebDriverWait(self.driver, times, poll_frequency).until(
             EC.visibility_of_element_located(locator))
         return True
     except Exception as e:
         #截图
         self.save_screenshot(doc)
         MyLog().info(e)
         return False
Exemplo n.º 19
0
 def test_submintClues_sucess(self, startApp):
     #切换到二手车
     SubmitCluesPage(startApp).submit_clues(vin_number)
     sleep(3)
     try:
         assert SubmitCluesPage(startApp).submitClue_success_isExit()
     except Exception as e:
         MyLog().info(e)
         raise
Exemplo n.º 20
0
 def get_toast_msg(self, text):
     toast_loc = "//*[contains(@text,'{}]')]".format(text)
     # 等待时要用presence_of_all_elements_located  不能用visibility_of_element_located 会报错
     try:
         WebDriverWait(self.driver, 10, 0.1).until(
             ec.presence_of_all_elements_located(
                 (MobileBy.XPATH, toast_loc)))
         return self.driver.find_element_by_xpath(toast_loc).text
     except:
         MyLog().error('没有找到匹配的toast!')
Exemplo n.º 21
0
 def __init__(self):
     # self.driver = driver
     self.log = MyLog()
     self.driver = Driver.driver
Exemplo n.º 22
0
# -*- coding: utf-8 -*-
# @Time : 2021/3/18 11:12
# @Author : demi
# @Email : [email protected]
# @File : basepage.py

from Common.my_log import MyLog
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import datetime
from Common import dir_config
import time

my_logger = MyLog()
# 1.封装基本函数--执行日志、异常处理、失败截图
# 2.所有页面的公共的部分
class BasePage:
    def __init__(self, driver):
        self.driver = driver

    # 等待元素可见
    def wait_eleVisible(self, locator, wait_times=30, poll_frequency=0.5, doc=""):
        """
        :param locator:元素定位。元组形式(元素定位类型,元素定位方式)
        :param times:等待时间
        :param poll_frequency:轮巡时间
        :param doc:模块名_页面名称_操作名称
        :return:None
        """
        my_logger.info('等待元素{0}可见'.format(locator))
        try:
Exemplo n.º 23
0
 def close_tab_already_opened(self):
     try:
         self.click_element(loc.tab_close)
         MyLog().info('已关闭已默认打开的tab!!!')
     except:
         MyLog().error('关闭已默认打开的tab失败!!!')
Exemplo n.º 24
0
class BasePage:

    def __init__(self, driver):
        self.driver = driver
        self.log = MyLog()

    # 等待元素可见
    def wait_eleVisible(self, locator, times=6, poll_frequency=0.5, doc=''):
        '''
        :param locator: 元素定位方式,元祖类型,如(BY.XPATH, XPTAH定位表达式)
        :param times: 最长等待时间
        :param poll_frequency: 多长时间查询一次
        :param doc: 操作的具体页面,doc的值传给except中的截图函数
        :return:
        '''
        self.log.info('{0}-->等待元素:{1}可见'.format(doc, locator))
        try:
            start = datetime.datetime.now()
            WebDriverWait(self.driver, times, poll_frequency).until(EC.visibility_of_element_located(locator))
            end = datetime.datetime.now()
            wait_times = (end - start).seconds
            self.log.info('{0}-->元素:{1}-->已可见,等待时长为{2}'.format(doc, locator, wait_times))
            return True
        except:
            self.log.error('等待元素:{}可见失败!'.format(locator))
            # 截图
            # self.save_screen_picture(doc)
            return False

    def wait_eleVisible_without_screen_picture(self, locator, times=20, poll_frequency=0.5, doc=''):
        '''
        :param locator: 元素定位方式,元祖类型,如(BY.XPATH, XPTAH定位表达式)
        :param times: 最长等待时间
        :param poll_frequency: 多长时间查询一次
        :param doc: 操作的具体页面,doc的值传给except中的截图函数
        :return:
        '''
        self.log.info('在首页判断元素:{0}是否可见'.format(locator))
        try:
            start = datetime.datetime.now()
            WebDriverWait(self.driver, times, poll_frequency).until(EC.visibility_of_element_located(locator))
            end = datetime.datetime.now()
            wait_times = (end - start).seconds
            self.log.info('在首页元素:{0}-->已可见,等待时长为{1}------该项已展开'.format(locator, wait_times))
        except:
            self.log.error('在首页等待元素:{}可见失败!------该项未展开'.format(locator))
            # 截图
            # self.save_screen_picture(doc)
            raise

    # 截图
    def save_screen_picture(self, doc):
        '''
        :param doc: 当前操作的页面,如登录页面
        :return: None
        '''
        # 图片名称:页面名称_操作名称_时间.png
        # file_path = dir_config.screenshot_dir
        # file_name = r"G:\PycharmProjects\dmp\Outputs\screenshots\{0}_{1}.png".format(doc, time)
        file_name = dir_config.screenshot_dir + \
                    "/{0}_{1}.png".format(doc, time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime(time.time())))
        try:
            self.driver.save_screenshot(file_name)
            self.log.info('截图成功,存放路径为:{}'.format(file_name))
        except:
            self.log.error('截图失败')
            raise

    # 等待元素存在
    def wait_elePresence(self):
        pass

    # 判断元素是否不存在与DOM树里面或不可见
    def invisibility_of_ele(self, locator, times=5, poll_frequency=0.5, doc=''):
        try:
            WebDriverWait(self.driver, times, poll_frequency).until(EC.invisibility_of_element_located(locator))
            self.log.info('{0}元素{1}不存在'.format(doc, locator))
        except:
            self.log.error('元素{}存在'.format(locator))

    # 查找元素--一个
    def get_element(self, locator, doc=''):
        self.wait_eleVisible(locator, doc=doc)
        try:
            return self.driver.find_element(*locator)
        except:
            self.log.error('查找元素:{}失败'.format(locator))
            self.save_screen_picture(doc)
            # raise
            return False

    # 查找元素--一组
    def get_elements(self, locator, doc=''):
        self.wait_eleVisible(locator, doc=doc)
        try:
            return self.driver.find_elements(*locator)
        except:
            self.log.error('查找元素:{}失败'.format(locator))
            self.save_screen_picture(doc)
            raise

    # 点击操作
    def click_element(self, locator, doc=''):
        ele = self.get_element(locator)
        self.log.info('{0}-->点击元素:{1}'.format(doc, locator))
        try:
            ele.click()
        except:
            self.log.error('点击元素:{}失败'.format(locator))
            self.save_screen_picture(doc)
            raise

    # 定位为一组元素时,点击第一个元素
    def click_elements(self, locator, doc=''):
        ele = self.get_elements(locator)
        try:
            ele.click()
            self.log.info('{0}-->点击元素:{1}'.format(doc, locator))
        except:
            self.log.error('点击元素:{}失败'.format(locator))
            self.save_screen_picture(doc)
            raise

    # 通过get_elements获取到的定位元素,进行点击操作,函数中传入的是get_elements获取到的值,而不是元素定位表达式
    def click_ele(self, ele, doc=''):
        try:
            ele.click()
            self.log.info('在{0}点击{1}成功'.format(doc, ele))
        except:
            self.log.error('在{}点击失败'.format(doc))

    # 输入操作
    def input_text(self, locator, text, doc=''):
        ele = self.get_element(locator, doc)
        self.log.info('在{0}-->元素:{1}进行输入操作'.format(doc, locator))
        try:
            ele.send_keys(text)
            self.log.info('在元素{0}上输入的值为-------->>>>>{1}'.format(locator, text))
        except:
            self.log.error('在元素{}上输入失败'.format(locator))
            self.save_screen_picture(doc)
            raise

    # 获取元素的文本内容
    def get_text(self, locator, doc=''):
        ele = self.get_element(locator, doc)
        self.log.info('在{0}中-->获取元素:{1}的文本内容'.format(doc, locator))
        try:
            self.log.info('获取到{0}元素的文本内容为-------->>>>>{1}'.format(locator, ele.text))
            return ele.text
        except:
            self.log.error('获取元素:{}的文本内容失败'.format(locator))
            self.save_screen_picture(doc)
            raise

    # 清空输入框
    def clear_input(self, locator, doc=''):
        ele = self.get_element(locator, doc)
        try:
            self.log.info('在{0}-->清空元素(**输入框**):{1}中的内容'.format(doc, locator))
            ele.clear()
        except:
            self.log.error('清空{}输入框失败'.format(locator))
            raise

    # 获取title
    def get_title(self, doc=''):
        self.log.info('获取当前页面的title')
        try:
            self.log.info('在当前页面获取到的title是-->{0}'.format(self.driver.title))
            return self.driver.title
        except:
            self.log.error('在当前页面获取title失败!')

    # 获取元素的属性值
    def get_element_attribute(self, locator, attribute):
        self.log.info('获取{}元素中{}属性的属性值'.format(locator, attribute))
        try:
            ele = self.get_element(locator)
            return ele.get_attribute(attribute)
        except:
            self.log.error('在当前页面获取title失败!')
            return False

    # alert处理
    def alert_action(self, action='accept'):
        if action == 'accept':
            self.driver.switch_to_alert().accept()
        else:
            self.driver.switch_to_alert().dismiss()

    # iframe切换
    def switch_iframe(self, iframe_ele_or_name_id):
        self.log.info('准备切换iframe')
        try:
            self.driver.switch_to.frame(iframe_ele_or_name_id)
            self.log.info('已切换到{}iframe'.format(iframe_ele_or_name_id))
        except:
            self.log.error('切换iframe失败')

    # 返回默认iframe
    def back_to_default_content(self):
        self.driver.switch_to.default_content()
        self.log.info("已切回到默认的iframe")

    # 获取当前窗口的句柄
    def get_current_window_handle(self):
        self.log.info('获取当前窗口的句柄')
        try:
            current_window_handle = self.driver.current_window_handle
            self.log.info('获取当前窗口的句柄成功!!!当前窗口句柄为{}'.format(current_window_handle))
            return current_window_handle
        except:
            self.log.error('获取当前窗口的句柄失败!!!')

    # 窗口切换--切换到最新的窗口
    def switch_to_new_window(self, c_window):
        # c_window = self.driver.current_window_handle()
        windows = self.driver.window_handles
        self.log.info('所有窗口的句柄分别为{}'.format(windows))
        try:
            for i in windows:
                if i != c_window:
                    self.driver.switch_to.window(i)
                    self.log.info('已切换到最新的窗口!!!窗口句柄为{}'.format(i))
        except:
            self.log.error('切换到最新的窗口失败!!!')

    # 返回之前的窗口
    def back_to_default_window(self, c_window):
        self.log.info('返回到默认窗口')
        try:
            self.driver.switch_to.window(c_window)
            self.log.info('返回到默认窗口成功!!!窗口句柄为{}'.format(c_window))
        except:
            self.log.error('返回到默认窗口失败!!!')

    # 上传操作
    def upload(self, filePath, browser_type="chrome"):
        '''
        通过pywin32模块实现文件上传的操作
        :param filePath: 文件的绝对路径
        :param browser_type: 浏览器类型(默认值为chrome)
        :return:
        如何使用:
        # 在打开上传弹窗后,直接调用 upload 方法,传需要上传文件的绝对路径即可,upload("文件路径")
        '''
        if browser_type.lower() == "chrome":
            title = "打开"
        elif browser_type.lower() == "firefox":
            title = "文件上传"
        elif browser_type.lower() == "ie":
            title = "选择要加载的文件"
        else:
            title = ""  # 这里根据其它不同浏览器类型来修改
        self.log.info('准备上传文件,文件的路径为{}'.format(filePath))
        try:
            # 找元素
            # 一级窗口"#32770","打开"
            dialog = win32gui.FindWindow("#32770", title)
            # 向下传递
            ComboBoxEx32 = win32gui.FindWindowEx(dialog, 0, "ComboBoxEx32", None)  # 二级
            comboBox = win32gui.FindWindowEx(ComboBoxEx32, 0, "ComboBox", None)  # 三级
            # 编辑按钮
            edit = win32gui.FindWindowEx(comboBox, 0, 'Edit', None)  # 四级
            # 打开按钮
            button = win32gui.FindWindowEx(dialog, 0, 'Button', "打开(&O)")  # 二级
            # 输入文件的绝对路径,点击“打开”按钮
            time.sleep(1)
            win32gui.SendMessage(edit, win32con.WM_SETTEXT, None, filePath)  # 发送文件路径
            time.sleep(1)
            win32gui.SendMessage(dialog, win32con.WM_COMMAND, 1, button)  # 点击打开按钮
            self.log.info('文件上传成功!!!')
        except:
            self.log.error('文件上传失败!!!')

    # 下拉框选择--一个定位元素定位到了多个下拉框
    def selects(self, locator, m, n, doc=''):
        '''
        :param locator:
        :param m: 选择定位到的第几个元素
        :param n: 选择下拉框中第几个元素
        :param doc: 日志中需输入的msg
        :return:
        '''
        # self.wait_eleVisible(locator)            0807注释
        ele = self.get_elements(locator)[m]
        try:
            Select(ele).select_by_index(n)
            self.log.info('在{0}下拉框中选择第{1}个选项成功'.format(doc, n+1))
        except:
            self.log.error('在{0}下拉框中选择第{1}个选项失败'.format(doc, n+1))
            raise

    # 下拉框选择--一个定位元素定位一个下拉框
    def select(self, locator, n=1):
        ele = self.get_element(locator)
        try:
            Select(ele).select_by_index(n)
            self.log.info('下拉框中选择选项成功')
        except:
            self.log.error('下拉框中选择选项失败')
            raise

    # 下拉框选择--一个定位元素定位一个下拉框
    def select_by_text(self, locator, text):
        ele = self.get_element(locator)
        try:
            # Select(ele).select_by_index(n)
            Select(ele).select_by_visible_text(text)
            self.log.info('下拉框中选择选项成功')
        except:
            self.log.error('下拉框中选择选项失败')
            raise

    # 刷新页面
    def refresh_page(self):
        try:
            self.driver.refresh()
            self.log.info('刷新页面')
        except:
            self.log.error('刷新页面失败')
            raise

    # 鼠标双击操作
    def double_click(self, locator):
        self.log.info('准备执行鼠标双击{}'.format(locator))
        try:
            ele = self.get_element(locator)
            ActionChains(self.driver).double_click(ele).perform()
            self.log.info('执行鼠标双击成功!!!')
        except:
            self.log.error('执行鼠标双击失败!!!')

    # 鼠标悬停到某个元素上
    def move_to_element(self, locator):
        self.log.info('准备将鼠标悬停在{}元素上'.format(locator))
        try:
            ele = self.get_element(locator)
            ActionChains(self.driver).move_to_element(ele).perform()
            self.log.info('准备将鼠标悬停在元素上成功!!!')
        except:
            self.log.error('准备将鼠标悬停在元素上失败!!!')

    # js操作
    def execute_script(self, element):
        self.log.info('准备移除{}元素的readonly属性'.format(element))
        try:
            self.driver.execute_script("arguments[0].removeAttribute('readonly')", element)
            self.log.info('移除{}元素的readonly属性成功!!!'.format(element))
        except:
            self.log.error('移除{}元素的readonly属性失败!!!'.format(element))

    # 输入框输入内容后,点击回车键
    def enter_button(self, locator):
        ele = self.get_element(locator)
        try:
            ele.send_keys(Keys.ENTER)
        except:
            raise
Exemplo n.º 25
0
 def __init__(self, driver):
     self.driver = driver
     self.log = MyLog()
Exemplo n.º 26
0
class BasePage:
    def __init__(self, driver):
        self.driver = driver
        self.log = MyLog()

    # 等待元素可见
    def wait_eleVisible(self, locator, times=20, poll_frequency=0.5, doc=''):
        '''
        :param locator: 元素定位方式,元祖类型,如(BY.XPATH, XPTAH定位表达式)
        :param times: 最长等待时间
        :param poll_frequency: 多长时间查询一次
        :param doc: 操作的具体页面,doc的值传给except中的截图函数
        :return:
        '''
        self.log.info('{0}-->等待元素:{1}可见'.format(doc, locator))
        try:
            start = datetime.datetime.now()
            WebDriverWait(self.driver, times, poll_frequency).until(
                EC.visibility_of_element_located(locator))
            end = datetime.datetime.now()
            wait_times = (end - start).seconds
            self.log.info('{0}-->元素:{1}-->已可见,等待时长为{2}秒'.format(
                doc, locator, wait_times))
        except:
            self.log.error('等待元素可见失败!')
            # 截图
            self.save_screen_picture(doc)
            raise

    # 截图
    def save_screen_picture(self, doc):
        '''
        :param doc: 当前操作的页面,如登录页面
        :return: None
        '''
        # 图片名称:页面名称_操作名称_时间.png
        file_name = dir_config.screenshot_dir + \
                    "/{0}_{1}.png".format(doc, time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime(time.time())))
        try:
            self.driver.save_screenshot(file_name)
            self.log.info('截图成功,存放路径为:{}'.format(file_name))
        except:
            self.log.error('截图失败')
            raise

    # 等待元素存在
    def wait_elePresence(self):
        pass

    #判断元素是否不存在与DOM树里面或不可见
    def invisibility_of_ele(self,
                            locator,
                            times=5,
                            poll_frequency=0.5,
                            doc=''):
        try:
            WebDriverWait(self.driver, times, poll_frequency).until(
                EC.invisibility_of_element_located(locator))
            self.log.info('{0}元素{1}不存在'.format(doc, locator))
        except:
            self.log.error('元素{}存在'.format(locator))

    # 查找元素
    def get_element(self, locator, doc=''):
        try:
            return self.driver.find_element(*locator)
        except:
            self.log.error('查找元素失败')
            self.save_screen_picture(doc)
            raise

    # 点击操作
    def click_element(self, locator, doc=''):
        ele = self.get_element(locator)
        self.log.info('{0}-->点击元素:{1}'.format(doc, locator))
        try:
            ele.click()
        except:
            self.log.error('点击元素失败')
            self.save_screen_picture(doc)
            raise

    # 输入操作
    def input_text(self, locator, text, doc=''):
        ele = self.get_element(locator, doc)
        self.log.info('在{0}-->元素:{1}进行输入操作'.format(doc, locator))
        try:
            ele.send_keys(text)
            self.log.info('输入的值为-->{}'.format(text))
        except:
            self.log.error('输入失败')
            self.save_screen_picture(doc)
            raise

    # 获取元素的文本内容
    def get_text(self, locator, doc=''):
        ele = self.get_element(locator, doc)
        self.log.info('在{0}-->获取元素:{1}的文本内容'.format(doc, locator))
        try:
            self.log.info('获取到的元素文本内容为-->{}'.format(ele.text))
            return ele.text
        except:
            self.log.error('获取元素文本内容失败')
            self.save_screen_picture(doc)
            raise

    #清空输入框
    def clear_input(self, locator, doc=''):
        ele = self.get_element(locator, doc)
        try:
            self.log.info('在{0}-->清空元素(**输入框**):{1}中的内容'.format(doc, locator))
            ele.clear()
        except:
            self.log.error('清空输入框失败')
            raise

    #获取title
    def get_title(self):
        self.log.info('获取页面的title')
        try:
            self.log.info('在页面获取到的title是-->{}'.format(self.driver.title))
            return self.driver.title
        except:
            self.log.error('获取页面的title失败!')

    # 获取元素的属性
    def get_element_attribute(self):
        pass

    # alert处理
    def alert_action(self, action='accept'):
        pass

    # iframe切换
    def switch_iframe(self, iframe_ele):
        try:
            self.driver.switch_to.frame(iframe_ele)
            self.log.info('已切换到{}iframe'.format(iframe_ele))
        except:
            self.log.error('切换iframe失败')

    #窗口切换--切换到最新的窗口
    def switch_to_new_window(self):
        self.log.info('切换到最新的窗口')
        try:
            self.all_h = self.driver.window_handles
            self.driver.switch_to.window(self.all_h[-1])
            self.log.info('已成功切换到最新的窗口!!!')
        except:
            self.log.error('切换到最新的窗口失败!!!')

    # 上传操作
    def upload_file(self):
        pass

    #执行JS
    def execute_js(self, js, doc=''):
        self.log.info('在{}通过js执行点击'.format(doc))
        try:
            self.driver.execute_script(js)
            self.log.info('在{}通过js执行点击-->成功!!!'.format(doc))
        except:
            self.log.error('在{}执行js点击失败'.format(doc))


# 滚动条处理