zoukankan      html  css  js  c++  java
  • Python3 Selenium自动化web测试 ==> 第五节 WebDriver高级应用 -- 使用JavaScript操作页面元素

    学习目的:


     

      中级水平技术提升

      在WebDriver脚本代码中执行JS代码,可以解决某些 .click()方法无法生效等问题

    正式步骤:


     

    Python3代码如下

    # -*-  coding:utf-8 -*-
    from selenium import webdriver
    from selenium.webdriver import ActionChains
    from selenium.webdriver.support.ui import Select
    from selenium.webdriver.common.keys import Keys
    from selenium.common.exceptions import WebDriverException
    import traceback
    import unittest
    import time
    
    
    class WebdriverAPI(unittest.TestCase):
        def setUp(self):
            # 每个用例都执行,在单个用例运行前执行
            #打开浏览器
            self.driver = webdriver.Chrome()
    
        def tearDown(self):
            #每个用例都执行,在单个用例运行后执行
            #退出浏览器
            self.driver.quit()
    
        def test_useJS(self):
            url = 'https://www.baidu.com/'
            self.driver.get(url)
            #构造JavaScript查找百度首页的搜索输入框的代码字符串
            searchInputBox_JS = "document.getElementById('kw').value='selenium';"
            searchButton_JS = "document.getElementById('su').click;"
            try:
                self.driver.execute_script(searchInputBox_JS)
                time.sleep(2)
                self.driver.execute_script(searchButton_JS)
                time.sleep(2)
                self.assertTrue('你想变得更优秀' in self.driver.page_source)
            except WebDriverException as e:
                print("页面中没有找到要操作的页面元素",traceback.priny_exc())
            except AssertionError:
                print("断言关键字不存在")
            except Exception :
                print(traceback.priny_exc())
    if __name__ == '__main__':
        unittest.main()
  • 相关阅读:
    Git基本操作二
    Git基本操作一
    Mysql查询一
    接口的token验证
    Laravel模型的一些小技巧
    AOP编程思想实现全局异常处理
    5.4 RegExp类型
    5.4.1 RegExp实例属性
    5.4.2 RegExp实例方法
    5.4.3 RegExp构造函数属性
  • 原文地址:https://www.cnblogs.com/wuzhiming/p/9114296.html
Copyright © 2011-2022 走看看