中級水平技術提高web
在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()