標籤:ror 實現 page == name nta 存在 bin ase
在webdriver指令碼代碼中執行JavaScript代碼,來實現對頁面元素的操作。此種方式主要用於解決在某些情況下,頁面元素的.click()方法無法生效等問題。
#!usr/bin/env python #-*- coding:utf-8 -*- """ @author: sleeping_cat@Contact : [email protected] """ #使用JavaScript操作頁面元素from selenium import webdriverfrom selenium.common.exceptions import WebDriverExceptionimport unittestimport traceback#匯入堆棧類import timeclass TestDemo(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome() def test_executeScript(self): url = ‘http://www.baidu.com‘ self.driver.get(url) searchInputBoxJS = ‘document.getElementById("kw").value="光榮之路";‘
#構造JavaScript尋找百度首頁的搜尋輸入框的代碼字串 searchButtonJS = ‘document.getElementById("su").click()‘
#構造JavaScript尋找百度首頁的搜尋按鈕的代碼字串 try: self.driver.execute_script(searchInputBoxJS)
#通過JavaScript代碼在百度首頁搜尋輸入框中輸入“光榮之路” time.sleep(2) self.driver.execute_script(searchButtonJS)
#通過JavaScript代碼單擊百度首頁上的搜尋按鈕 time.sleep(2) self.assertTrue(‘百度百科‘ in self.driver.page_source) except WebDriverException as e: print("在頁面中沒有找到要操作的頁面元素" ,traceback.print_exc())#列印異常的堆棧資訊 except AssertionError as e: print(‘頁面不存在斷言的關鍵字串‘) except Exception as e: print(traceback.print_exc())#發生其他異常時,列印異常堆棧資訊 def tearDown(self): self.driver.quit()if __name__ == ‘__main__‘: unittest.main()
使用JavaScript操作頁面元素