自動(dòng)化測試執(zhí)行過程中,難免會(huì)有錯(cuò)誤/異常出現(xiàn),比如測試腳本沒有發(fā)現(xiàn)對(duì)應(yīng)元素,則會(huì)立刻拋出NoSuchElementException異常。這時(shí)不要怕,肯定是測試腳本或者測試環(huán)境哪里出錯(cuò)了!那如何處理才是關(guān)鍵?因?yàn)橐话阒皇蔷植坑袉栴},為了讓腳本繼續(xù)執(zhí)行,so我們可以用try...except...raise捕獲異常。該捕獲異常后可以打印出相應(yīng)的異常原因,這樣以便于分析異常原因。
下面將舉例說明,當(dāng)異常拋出后將信息打印在控制臺(tái),同時(shí)截取當(dāng)前瀏覽器窗口,作為后續(xù)bug的依據(jù)給相應(yīng)開發(fā)人員更好下定位問題。代碼如下:
import unittestfrom selenium import webdriverfrom selenium.common.exceptions import NoSuchElementException #導(dǎo)入NoSuchElementExceptionclass ExceptionTest(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome() self.driver.get("https://www.baidu.com") def test_exception(self): driver = self.driver try: search_text = driver.find_element_by_id("ss") self.assertEqual('百度一下', search_text.get_attribute("value")) except NoSuchElementException: file_name = "no_such_element.png" #driver.save_screenshot(file_name) driver.get_screenshot_as_file(file_name) raise #拋出異常,注釋后則不拋出異常 def tearDown(self): self.driver.quit()if __name__ == '__main__': unittest.main(verbosity=2)運(yùn)行有異常,結(jié)果如下:

上面代碼中用到WebDriver內(nèi)置的捕獲屏幕并保存的方法,如這里的save_screenshot(filename)方法和save_screenshot_as_file(filename)方法,在測試異常拋出時(shí),同時(shí)截取瀏覽器屏幕并以自定義的圖片文件名保存在指定路徑(上面代碼為當(dāng)前路徑)。
又如當(dāng)一個(gè)元素呈現(xiàn)在DOM,但它是不可見的,不能與之進(jìn)行交互,異常將拋出,以百度首頁的登錄為例,當(dāng)元素不能不可見時(shí),拋出ElementNotVisibleException的異常,代碼如下:
import unittestfrom selenium import webdriverfrom selenium.common.exceptions import ElementNotVisibleException #導(dǎo)入ElementNotVisibleExceptionclass ExceptionTest(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome() self.driver.get("https://www.baidu.com") def test_exception(self): driver = self.driver try: login = driver.find_element_by_name("tj_login") login.click() except ElementNotVisibleException: raise def tearDown(self): self.driver.quit()if __name__ == '__main__': unittest.main(verbosity=2)運(yùn)行有異常,結(jié)果如下:

下面將列舉selenium常見的異常:

總結(jié)
以上所述是小編給大家介紹的Python 中的Selenium異常處理實(shí)例,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)VEVB武林網(wǎng)網(wǎng)站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選