這篇文章主要介紹了關於PHPPython 中的Selenium異常處理,有著一定的參考價值,現在分享給大家,有需要的朋友可以參考一下
自動化測試執行過程中,難免會有錯誤/異常出現,比如測試指令碼沒有發現對應元素,則會立刻拋出NoSuchElementException異常。這時不要怕,肯定是測試指令碼或者測試環境哪裡出錯了!那如何處理才是關鍵?因為一般只是局部有問題,為了讓指令碼繼續執行,so我們可以用try...except...raise捕獲異常。該捕獲異常後可以列印出相應的異常原因,這樣以便於分析異常原因。
下面將舉例說明,當異常拋出後將資訊列印在控制台,同時截取當前瀏覽器視窗,作為後續bug的依據給相應開發人員更好下定位問題。代碼如下:
import unittestfrom selenium import webdriverfrom selenium.common.exceptions import NoSuchElementException #匯入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)
運行有異常,結果如下:
上面代碼中用到WebDriver內建的捕獲螢幕並儲存的方法,如這裡的save_screenshot(filename)方法和save_screenshot_as_file(filename)方法,在測試異常拋出時,同時截取瀏覽器螢幕並以自訂的圖片檔案名稱儲存在指定路徑(上面代碼為當前路徑)。
又如當一個元素呈現在DOM,但它是不可見的,不能與之進行互動,異常將拋出,以百度首頁的登入狀態例,當元素不能不可見時,拋出ElementNotVisibleException的異常,代碼如下:
import unittestfrom selenium import webdriverfrom selenium.common.exceptions import ElementNotVisibleException #匯入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)
運行有異常,結果如下:
下面將列舉selenium常見的異常: