unittest+js自動(dòng)化測(cè)試高級(jí)應(yīng)用

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容