使用selenium 與 js還有聯(lián)用來(lái)操作頁(yè)面元素
from selenium import webdriver
from selenium.common.exceptionsimport WebDriverException
import unittest
import traceback
import time
class TestDemo(unittest.TestCase):
? ? def setUp(self):
? ? ? ? #啟動(dòng)Chrome瀏覽器
? ? ? ? self.driver= webdriver.Chrome(executable_path='C:\Python\Python37\chromedriver.exe')
def test_excuteScript(self):
? ? ? ? #訪問(wèn)baidu首頁(yè)
? ? ? ? url= 'http://www.baidu.com'
? ? ? ? self.driver.get(url)
#構(gòu)造js查找百度首頁(yè)的搜索輸入框的代碼字符串
? ? ? ? searchInputBoxJS= "document.getElementById('kw').value='光榮之路';"
? ? ? ? #構(gòu)造js查找百度首頁(yè)的搜索按鈕的代碼字符串
? ? ? ? searchInputButtonJS = "document.getElementById('su').click()"
? ? ? ? try:
? ? ? ? ? ? #通過(guò)js代碼在百度首頁(yè)搜索輸入框中輸入“光榮之路”
? ? ? ? ? ? self.driver.execute_script(searchInputBoxJS)
time.sleep(2)
#通過(guò)js代碼單擊百度首頁(yè)上的搜索按鈕
? ? ? ? ? ? self.driver.execute_script(searchInputBoxJS)
self.assertTrue("百度百科" in self.driver.page_source)
except WebDriverException as e:
? ? ? ? ? ? #當(dāng)定位失敗時(shí),會(huì)拋出WebdriverException異常
? ? ? ? ? ? print("頁(yè)面中沒(méi)有找到要操作的頁(yè)面元素", traceback.print_exc())
except AssertionError as e:
? ? ? ? ? ? #發(fā)生其他異常時(shí),打印異常堆棧信息
? ? ? ? ? ? print(traceback.print_exc())
def tearDown(self):
? ? ? ? #t退出Chrome瀏覽器
? ? ? ? self.driver.quit()
if __name__== '__main__':
? ? unittest.main()