zoukankan      html  css  js  c++  java
  • JavaScript在web自动化测试中的应用

    前言

    JS的全称JavaScript,是一种运行在浏览器中的解释型脚本语言,通常用来实现web前端页面的基本功能,对于前端开发人员是不得不掌握的一门基本技能,但是对于做web自动化测试的人员来说,如果为了实施自动化测试专门研究JS的脚本语法不仅浪费时间,也偏离了我们的工作重心,所以今天就给大家总结一下,在web自动化测试中常用的一些JS脚本,只要掌握这些脚本的使用,无需再为专门学习js脚本而花费太多时间,优秀程序员的素质是什么?有现成的直接用,绝不浪费时间自己写!^_^ 开玩笑的,俗话说技多不压身,多掌握一门技能,只有好处没坏处。正文开始!

    窗口滚动

    用途:滑动web页面

    def scrollTo(x, y):
        js = """
        window.scrollTo("{x}", "{y}")
        """.format(x=x, y=y)
        driver.execute_script(js)

    参数说明

    x:屏幕向右移动的距离

    y:屏幕向下移动的距离

    移除属性

    用途:以下方法可以删除元素的任何属性,主要用来移除时间控件的readonly属性

    def remove_attribute(css, attribute, index=0):
        js = """
        var element = document.querySelectorAll("{css}")[{index}];
            element.removeAttribute("{attr}");
        """.format(css=css, index=index, attr=attribute)
        driver.execute_script(js)

    参数说明

    css::css表达式

    index:索引值,默认0,标识第一个元素

    attribute:元素的某个属性,比如readonly,value,name等

    高亮元素

    用途:方便用户查看当前操作的是哪个页面元素,也方便测试人员定位问题

    def height_light(css, index=0):
        js = """
        var element = document.querySelectorAll("{css}")[{index}];
            element.style.border="2px solid red";
        """.format(css=css, index=index)
        driver.execute_script(js)

    参数说明

    css:css表达式

    index:索引值,默认0,标识第一个元素

    点击元素

    用途:由于web自动化的最大问题就是稳定性比较差,有些时候使用selenium无法点击元素,因此我们可以使用JS实现元素的点击操作

    def click(css, index=0):
        js = """var element = document.querySelectorAll("{css}")[{index}];
                   element.click();""".format(css=css, index=index)
        driver.execute_script(js)

    参数说明

    css:css表达式

    index:索引值,默认0,标识第一个元素

    清除输入框内容

    用途:用来清除输入框的内容

    def clear(css, index=0):
        js = """var element = document.querySelectorAll("{css}")[{index}];
                    element.value = "";""".format(css=css, index=index)
        driver.execute_script(js)

    参数说明

    css:css表达式

    index:索引值,默认0,标识第一个元素

    输入内容

    用途:输入框中输入内容

    def input(self, css, value, index=0):
        js = """var element = document.querySelectorAll("{css}")[{index}];
                    element.value = "{value}";""".format(css=css, index=index, value=value)
        driver.execute_script(js)

    参数说明

    css:css表达式

    value:待输入的数据

    index:索引值,默认0,标识第一个元素

    说明

    以上所有的JS操作,还可以结合selenium中的WebElement按照以下方式实现,因为JS中查找元素的方法有限,比如xpath定位,在js中不存在

    如滚动页面

    def scrollTo(self, element, x, y):
        js = """
        arguments[0].scrollTo("{}", "{}")
        """.format(x, y)
        driver.execute_script(js, element)

    参数说明

    element:通过selenium中的定位方法查找到的WebElement元素对象

    arguments[0]:代表execute_script()方法的第二个参数

    测试代码

    我们简单的写个测试脚本来测试一下以上JS脚本是否能够顺利执行

    js_element.py

    """
    ------------------------------------
    @Time : 2019/8/23 19:00
    @Auth : linux超
    @File : js_element.py
    @IDE  : PyCharm
    @Motto: Real warriors,dare to face the bleak warning,dare to face the incisive error!
    @QQ   : 28174043@qq.com
    @GROUP: 878565760
    ------------------------------------
    """
    
    
    class CssElement(object):
    
        driver = None
    
        def __init__(self, css, index=None, describe=None):
            self.css = css
            if index is None:
                self.index = 0
            else:
                self.index = index
            self.desc = describe
    
        def __get__(self, instance, owner):
            if instance is None:
                return None
            global driver
            driver = instance.driver
            return self
    
        def clear(self):
            """
            清除内容
            """
            js = """var elm = document.querySelectorAll("{css}")[{index}];
                        elm.style.border="2px solid red";
                        elm.value = "";""".format(css=self.css, index=self.index)
            driver.execute_script(js)
    
        def input(self, value):
            """
            输入内容
            """
            js = """var elm = document.querySelectorAll("{css}")[{index}];
                        elm.style.border="2px solid red";
                        elm.value = "{value}";""".format(css=self.css, index=self.index, value=value)
            driver.execute_script(js)
    
        def click(self):
            """
            点击元素
            """
            js = """var elm = document.querySelectorAll("{css}")[{index}];
                       elm.style.border="2px solid red";
                       elm.click();""".format(css=self.css, index=self.index)
            driver.execute_script(js)
    
        def remove_attribute(self, attribute):
            """
            删除某个元素的属性,比如日期空间的readonly属性
            """
            js = """
            var elm = document.querySelectorAll("{css}")[{index}];
                elm.removeAttribute("{attr}");
            """.format(css=self.css, index=self.index, attr=attribute)
            driver.execute_script(js)
    
        @staticmethod
        def remove_attr(element, attribute):
            js = """
            arguments[0].removeAttribute("{attr}");
            """.format(attr=attribute)
            driver.execute_script(js, element)
    
        @staticmethod
        def scrollTo(x, y):
            js = """
            window.scrollTo("{}", "{}")
            """.format(x, y)
            driver.execute_script(js)
    
        @staticmethod
        def window_scroll(element, x, y):
            js = """
            arguments[0].scrollTo("{}", "{}")
            """.format(x, y)
            driver.execute_script(js, element)
    
        def height_light(self):
            js = """
            var element = document.querySelectorAll("{css}")[{index}];
                element.style.border="2px solid red";
            """.format(css=self.css, index=self.index)
            driver.execute_script(js)
    
        @staticmethod
        def height_lig(element):
            js = """
            arguments[0].style.border="2px solid red";
            """
            driver.execute_script(js, element)
    
    
    if __name__ == '__main__':
        pass

    用例

    test_js.py

    """
    ------------------------------------
    @Time : 2019/8/22 16:51
    @Auth : linux超
    @File : test_js.py
    @IDE  : PyCharm
    @Motto: Real warriors,dare to face the bleak warning,dare to face the incisive error!
    @QQ   : 28174043@qq.com
    @GROUP: 878565760
    ------------------------------------
    """
    import time
    from selenium.webdriver.remote.webdriver import WebDriver
    import unittest
    from selenium import webdriver
    
    from javascript.js_element import CssElement
    
    
    class Base(object):
        window = CssElement
    
        def __init__(self, driver: WebDriver):
            self.driver = driver
    
        def load_url(self, url):
            return self.driver.get(url)
    
    
    class BaiDuPage(Base):
        search_input = CssElement("#kw", describe="百度搜索框")
        search_button = CssElement("#su", describe="百度按钮")
    
        def search(self):
            self.search_input.height_light()
            self.search_input.clear()
            time.sleep(2)  # 为了看到效果
            self.search_input.input("linux超")
            time.sleep(2)
            self.search_button.height_light()
            self.search_button.click()
            time.sleep(2)
            self.window.scrollTo("0", "500")
            time.sleep(2)  # 为了看到效果
    
    
    class ChinaRailway(Base):
        data_input = CssElement("#train_date", describe="日期控件")
    
        def input_date(self, date):
            self.data_input.height_light()
            self.data_input.remove_attribute("readonly")
            self.data_input.input(date)
            time.sleep(2)  # 为了看到效果
    
    
    class TestJs(unittest.TestCase):
    
        def setUp(self):
            self.driver = webdriver.Firefox()
            self.driver.maximize_window()
            self.driver.implicitly_wait(20)
            self.bai_du_page = BaiDuPage(self.driver)
            self.china_railway = ChinaRailway(self.driver)
    
        def test_search(self):
            """百度搜索"""
            self.bai_du_page.load_url("https://www.baidu.com")
            self.bai_du_page.search()
    
        def test_china_railway(self):
            """12306日期"""
            self.china_railway.load_url("https://www.12306.cn/index/")
            time.sleep(5)  #
            self.china_railway.input_date("2021-01-01")
    
        def tearDown(self):
            self.driver.quit()
    
    
    if __name__ == '__main__':
        unittest.main()

    执行效果及输出

    总结

    以上所有的操作仅支持CSS表达式, 当然你可以修改替换querySelectorAll方法为getElementById, getElementByClassName等,但是需要注意使用getElementById时,不需要index参数;

    Js相对于selenium的控制页面元素,执行速度更快,而且当遇到selenium比较难处理的操纵时,可以考虑使用js代码来实现,当然还是需要你懂点Js代码,不懂也没关系,掌握以上代码完全够你解决实际问题

  • 相关阅读:
    python主要探索函数
    数据分析分析方法
    监控hadoop任务结果shell脚本
    shell编程
    hadoop介绍
    数据探索
    Python数据分析简介
    数据挖掘基础篇之整体思路
    sqlAlchemy
    python md5 加密
  • 原文地址:https://www.cnblogs.com/linuxchao/p/linuxchao-js.html
Copyright © 2011-2022 走看看