zoukankan      html  css  js  c++  java
  • python自动化之UI自动化框架搭建二(关键字驱动)

    九、修改util报中的WaitUtil.py文件,如:iframe弹框;根据实际情况判断是否使用

    # encoding=utf-8
    
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    
    # 实现智能等待页面元素出现
    class WaitUtil(object):
    
        def __init__(self, driver):
    
            self.locationTypeDict = {
                "xpath": By.XPATH,
                "id": By.ID,
                "name": By.NAME,
                "class_name": By.CLASS_NAME,
                "tag_name": By.TAG_NAME,
                "link_text": By.LINK_TEXT,
                "partial_link_text": By.PARTIAL_LINK_TEXT
            }
    
            self.driver = driver
            self.wait = WebDriverWait(self.driver, 10)
    
    
        def presenceOfElementLocated(self, locatorMethod, locatorExpression, *args):
    
            # 显示等待页面元素出现在DOM中,但不一定可见,存在则返回该页面元素对象
    
            try:
                if self.locationTypeDict.has_key(locatorMethod.lower()):
                    self.wait.until(
                        EC.presence_of_element_located((
                            self.locationTypeDict[locatorMethod.lower()],
                            locatorExpression)))
                else:
                    raise TypeError('未找到定位方式,请确认定位方法是否正确')
            except Exception as e:
                raise e
    
    
        def frame_available_and_switch_to_it(self, locationType, locatorExpression):
            """检查fram弹框是否存在,存在则切换frame控件中"""
    
            try:
                self.wait.until(EC.frame_to_be_available_and_switch_to_it
                                ((self.locationTypeDict[locationType.lower()],
                                  locatorExpression)))
            except Exception as e:
                raise e
    
    
        def visibility_element_located(self, locationType, locatorExpression):
    
            # 显示等待页面元素出现在DOM中,并且可见,存在则返回该页面元素对象
            try:
                element = self.wait.until(EC.visibility_of_element_located
                                          ((self.locationTypeDict[locationType.lower()],
                                            locatorExpression)))
                return element
            except Exception as e:
                raise e
    
    
    if __name__ == '__main__':
        from selenium import webdriver
        import time
    
        driver = webdriver.Chrome()
        driver.get("***")
        waitUtil = WaitUtil(driver)
        # waitUtil.frame_available_and_switch_to_it("id", "x-URS-iframe")
        e = waitUtil.visibility_element_located("xpath", "//*[@id='ssoLoginMode']/li[2]/a")
        e.click()
        # time.sleep(5)
        driver.quit()

    十、KeyWordsFrameWork工程中新建一个action的python package,并在此包中新建一个PageAction.py文件,用于实现具体的页面动作,比如再输入框中输入数据,单击页面按钮等

    # encoding=utf-8
    
    from selenium import webdriver
    from KeyWordsFrameWork.util.ObjectMap import getElement
    from KeyWordsFrameWork.util.DirAndTime import *
    from KeyWordsFrameWork.util.WaitUtil import WaitUtil
    from selenium.webdriver.chrome.options import Options
    import time
    
    # 定义全局变量driver
    driver = None
    # 全局等待类实例对象
    waitUtil = None
    
    
    def open_browser(browsername='chrome', *args):
        # 打开浏览器
        global driver, waitUtil
        try:
            if browsername.lower() == 'chrome':
    
                driver = webdriver.Chrome()
            waitUtil = WaitUtil(driver)
        except Exception as e:
            raise e
    
    
    def visit_url(url, *args):
    
        # 访问某个网站
        global driver
        try:
            driver.get(url)
        except Exception as e:
            raise e
    
    
    def close_browser(*args):
        # 关闭浏览器
        global driver
        try:
            driver.quit()
        except Exception as e:
            raise e
    
    
    def sleep(sleepSeconds, *args):
        # 强制等待
        try:
            time.sleep(int(sleepSeconds))
    
        except Exception as e:
            raise e
    
    
    def clear(locationType, locatorExpression, *args):
        # 清楚输入框默认内容
        global driver
        try:
            getElement(driver, locationType, locatorExpression).clear()
        except Exception as e:
            raise e
    
    
    def input_string(locationType, locatorExpression, inputContent):
        # 输入数据
        global driver
        try:
            getElement(driver, locationType,
                        locatorExpression).send_keys(inputContent)
        except Exception as e:
            raise e
    
    
    def click(locationType, locatorExpression, *args):
        # 单击页面元素
        global driver
        try:
            element = getElement(driver, locationType, locatorExpression)
    
            # 防止点击时ElementClickInterceptedException异常,元素被遮挡;移动到这个元素后再点击
            webdriver.ActionChains(driver).move_to_element(element).click(element).perform()
    
        #     if args is None:
        #         element.click()
        #     else:
        #         # 当元素无法可以定位到但被遮挡无法点击时,传入*args使用下面方法
        #         driver.execute_script("arguments[0].click();", element)
        except Exception as e:
            raise e
    
    
    def assert_string_in_pagesource(assertString, *args):
        # 断言页面源码是否存在某个关键字或关键字符串
        global driver
    
        try:
            assert assertString in driver.page_source, 
                '%s not found in page source!' % assertString
    
        except AssertionError as e:
            raise e
        except Exception as e:
            raise e
    
    
    def assert_title(titleStr, *args):
        # 断言页面标题是否存在给定的关键字符串
        global driver
        try:
            assert titleStr in driver.title, 
                '%s not found in title!' % titleStr
        except AssertionError as e:
            raise e
        except Exception as e:
            raise e
    
    
    def get_title(*args):
        # 获取页面标题
        global driver
        try:
            return driver.title
        except Exception as e:
            raise e
    
    
    def getPageSource(*args):
        # 获取页面源码
        global driver
        try:
            return driver.page_source
        except Exception as e:
            raise e
    
    
    def switch_to_frame(locationType, frameLocatorExpression, *args):
        # 切换进入frame
        global driver
        try:
            driver.switch_to.frame(getElement(driver, locationType,
                                              frameLocatorExpression))
        except Exception as e:
            print("frame error")
            raise e
    
    
    def switch_to_default_content(*args):
        # 切出frame
        global driver
        try:
            driver.switch_to.default_content()
    
        except Exception as e:
            raise e
    
    
    def maximzie_browser():
        # 窗口最大化
        global driver
        try:
            driver.maximize_window()
        except Exception as e:
            e
    
    
    def capture_screen(*args):
        # 截取屏幕图片
        global driver
        currTime = getCurrentTime()
        picNameAndPath = str(createCurrentDateDir()) + '/' + str(currTime) + '.png'
    
        try:
            driver.get_screenshot_as_file(picNameAndPath.replace('/', '/'))
        except Exception as e:
            raise e
        else:
            return picNameAndPath
    
    
    # 显示等待页面元素出现在DOM中,但并不一定可见,存在则返回该页面元素对象
    def waitPresenceOfElementLocated(locationType, locatorExpression, *args):
    
        global waitUtil
        try:
            waitUtil.presenceOfElementLocated(locationType, locatorExpression)
        except Exception as e:
            raise e
    
    
    # 检查fram弹框是否存在,存在则切换frame控件中
    def waitFrameToBeAvailableAndSwitchToIt(locationType, locatorExpression):
    
        global waitUtil
        try:
            waitUtil.frame_available_and_switch_to_it(locationType, locatorExpression)
        except Exception as e:
            raise e
    
    
    # 显示等待页面元素出现在DOM中,并且可见,存在则返回该页面元素对象
    def waitVisibilityOfElementLocated(locationType, locatorExpression):
    
        global waitUtil
        try:
            waitUtil.visibility_element_located(locationType, locatorExpression)
        except Exception as e:
            raise e

    十一、修改testScripts包中的TestCreatBuilding.py

    # encoding=utf-8
    from KeyWordsFrameWork.action.PageAction import *
    
    
    def TestCreatBuild():
    
        # 启动chrome浏览器
        open_browser('chrome')
        maximzie_browser()
    
        # 访问登录页
        visit_url('https:****.com')
        sleep(5)
    
        assert_string_in_pagesource('***')
        print('访问登录页成功')
    
        # wait = WaitUtil(driver)
    
        # 切换登录方式
        click("xpath", "//*[@id='ssoLoginMode']/li[2]/a")
    
        print('输入用户名')
        input_string("xpath", "//*[@id='username']", '****')
    
        print('输入登录密码')
        input_string("xpath", "//*[@id='password']", '****')
    
        print('登录')
        click('xpath', "//*[@id='accountLogin']/button")
    
        # 等待*秒,验证页面加载完成
        sleep(5)
        assert_string_in_pagesource("***")
        print("登录成功")
    
        # 切换到building页面
        click('xpath', '//*[@id="app"]/div/section/aside/div/ul/li[3]/div/span/span')
        sleep(1)
        click('xpath', '//*[@id="/area$Menu"]/li[1]/a/span')
    
        sleep(5)
        assert_title("***")
        print('进入***页面')
    
        # 点击创建按钮
        click('xpath', '//*[@id="root"]/div/section/section/section/'
                       'main/div/div[2]/div/div/div[3]/div/div[1]/div[1]/'
                       'button')
        sleep(3)
        # 选择地址
        click('xpath', '//*[@id="root"]/div/section/section/section/main/'
                       'div/div[2]/div/div/div/form/div[1]/div[3]/div[1]/'
                       'div[1]/div/div[2]/div/span/span/span')
        # 选择省市区
        click('xpath', '//li[text()="北京"]')
        click('xpath', '/html/body/div[2]/div/div/div/ul[2]/li')
        click('xpath', '/html/body/div[2]/div/div/div/ul[3]/li[3]')
        # 录入详细地址
        input_string('xpath', '//*[@id="address"]', '****')
        # 录入building名称
        input_string('xpath', '//*[@id="name"]', '测试测试')
        # 点击building定位
        click('xpath', '//*[@id="buildAdressMarker"]/button')
        sleep(3)
        # 点击提交按钮
        click('xpath', '//*[@id="root"]/div/section/section/section/main/'
                       'div/div[2]/div/div/div/form/div[5]/div/button[1]')
    
        sleep(3)
    
        # 关闭保存成功提示
        click('xpath', '//button/span[text()="OK"]', False)
    
        sleep(3)
        # 校验数据新建成功
        assert_string_in_pagesource('测试测试')
        print('新建成功')
    
    
        close_browser()
    
    
    
    
    if __name__ == "__main__":
        TestCreatBuild()
  • 相关阅读:
    Redux
    版本控制(.git + .svn + SourceTree)
    前端埋点
    前端IDE:VSCode + WebStorm
    浏览器
    Mutation Observer
    函数节流与函数去抖
    React 初识
    Ajax
    JS
  • 原文地址:https://www.cnblogs.com/huwang-sun/p/15340273.html
Copyright © 2011-2022 走看看