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()

 

转载于:https://www.cnblogs.com/wuzhiming/p/9114296.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值