• 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()
  • 相关阅读:
    tp5 生成数据表
    tp5 事务
    时间
    api json
    php 函数学习
    win7 安装Ubuntu18.04 双系统后无法引导win7
    vite笔记
    tp5 excel导出
    tp5 sql查询
    idea 停止运行程序
  • 原文地址:https://www.cnblogs.com/wuzhiming/p/9114296.html
Copyright © 2020-2023  润新知