Python 中的Selenium異常處理

來源:互聯網
上載者:User
這篇文章主要介紹了關於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常見的異常:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.