前言
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):
- Windows = 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.Windows.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 代码, 不懂也没关系, 掌握以上代码完全够你解决实际问题
来源: https://www.cnblogs.com/linuxchao/p/linuxchao-js.html