python自动化之UI自动化框架搭建二(关键字驱动)

摘要:
9、 修改util消息中的WaitUtil.py文件,如iframe弹出框;判断是否使用#encoding=utf-8fromsenium。webdriver。常见的通过从硒中导入。webdriver。支持uiimportWebDriverWaitfromselenium。webdriver。根据实际情况预计支持导入_

九、修改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()

免责声明:文章转载自《python自动化之UI自动化框架搭建二(关键字驱动)》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇关于C#调用C++ 的DLL传送字符串显示乱码的解决mysql批量更新下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

Ansible之路——第四章:Host Inventory

Ansible 可同时操作属于一个组的多台主机,组和主机之间的关系通过 inventory 文件配置. 默认的文件路径为 /etc/ansible/hosts。 除默认文件外,还可以同时使用多个 inventory 文件,也可以从动态源,或云上拉取 inventory 配置信息。 4.1 静态Inventory文件  静态Inventory指的是在文件/...

NumPy之:标量scalars

目录 简介 scalar类型的层次结构 内置Scalar类型 boolean Integers Unsigned integers Floating-point numbers Complex floating-point numbers Python 对象 可变长度数据类型 简介 Python语言中只定义了特定数据类的一种类型(比如只有...

pyspark 安装配置【linux && win】

一、windows 安装 1、下载spark http://mirrors.tuna.tsinghua.edu.cn/apache/spark/spark-2.3.1/spark-2.3.1-bin-hadoop2.7.tgz 2、配置spark 环境变量 set SPARK_HOME=d:spark2.3.1set PATH=%SPARK_HO...

python下进行10进制转16进制不带0x并且将16进制转成小端序

前记   python涉及到和硬件互交的部分,一般是需要发送十六进制的帧长的。所以,python这个转换还是经常使用的。笔者在这里遇到了一个问题。就做一个记录吧。 基本方法:  假如你熟悉python的话,这个是非常简单的,就只需要把int类型的数取从第二位开始的数据就行了:如下所述: hex(28)[2:] 测试实例: import sys arr...

linux下使用virtualenv虚拟独立python环境

virtualenv可以搭建虚拟且独立的python环境,可以使每个项目环境与其他项目独立开来,保持环境的干净,解决包冲突问题。 一、安装virtualenv virtualenv实际上是一个python包,所以我们可以用easy_install或者pip安装。下面介绍在CentOS系统上的安装方法。 easy_install安装方式: 1 2...

python中使用multipart/form-data请求上传文件

最近测试的接口是上传文件的接口,上传单个文件,我主要使用了2种方法~ 接口例如: URL: http://www.baidu.com/*** method:post 参数: {"salary":19,"file":{}} 1、使用Python的requests上传表单数据和文件 data={"salary":salary} files={'file...