Python Selenium之异常处理

  自动化测试执行过程中,难免会有错误/异常出现,比如测试脚本没有发现对应元素,则会立刻抛出NoSuchElementException异常。这时不要怕,肯定是测试脚本或者测试环境哪里出错了!那如何处理才是关键?因为一般只是局部有问题,为了让脚本继续执行,so我们可以用try...except...raise处理并捕获异常。该捕获异常后可以打印出相应的异常原因,这样以便于分析异常原因。

  下面将举例说明,当异常抛出后将信息打印在控制台,同时截取当前浏览器窗口,作为后续bug的依据给相应开发人员更好下定位问题。代码如下:

 1 import unittest
 2 from selenium import webdriver
 3 from selenium.common.exceptions import NoSuchElementException    #导入NoSuchElementException
 4 
 5 class ExceptionTest(unittest.TestCase):
 6     def setUp(self):
 7         self.driver = webdriver.Chrome()
 8         self.driver.get("https://www.baidu.com")
 9 
10     def test_exception(self):
11         driver = self.driver
12         try:
13             search_text = driver.find_element_by_id("ss")
14             self.assertEqual('百度一下', search_text.get_attribute("value"))
15         except NoSuchElementException:
16             file_name = "no_such_element.png"
17             #driver.save_screenshot(file_name)
18             driver.get_screenshot_as_file(file_name)  
19             raise    #抛出异常,注释后则不抛出异常
20 
21     def tearDown(self):
22         self.driver.quit()
23 
24 if __name__ == '__main__':
25     unittest.main(verbosity=2)

  运行过程有异常抛出,结果如下:

  上面代码中用到WebDriver内置的捕获屏幕并保存的方法,如这里的save_screenshot(filename)方法和save_screenshot_as_file(filename)方法,在测试异常抛出时,同时截取浏览器屏幕并以自定义的图片文件名保存在指定路径(上面代码为当前路径)。如果上面测试脚本后面还有其它定义的test()也将会继续运行至所有方法结束。即在有异常测试后不会停留在当前,会继续运行下去。

  又如当一个元素呈现在DOM,但它是不可见的,不能与之进行交互,异常将抛出,以百度首页的登录为例,当元素是不可见时,抛出ElementNotVisibleException的异常,代码如下:

 1 import unittest
 2 from selenium import webdriver
 3 from selenium.common.exceptions import ElementNotVisibleException    #导入ElementNotVisibleException
 4 
 5 class ExceptionTest(unittest.TestCase):
 6     def setUp(self):
 7         self.driver = webdriver.Chrome()
 8         self.driver.get("https://www.baidu.com")
 9 
10     def test_exception(self):
11         driver = self.driver
12         try:
13             login = driver.find_element_by_name("tj_login")
14             login.click()
15         except ElementNotVisibleException:
16             raise    
17 
18     def tearDown(self):
19         self.driver.quit()
20 
21 if __name__ == '__main__':
22     unittest.main(verbosity=2)

  运行过程有异常抛出,结果如下:

  下面将列举selenium常见的异常:

  如果想了解更多异常,可以直接到你的python安装路径下面的\Lib\site-packages\selenium\common,打开exceptions.py文件~

  也可以参考:https://seleniumhq.github.io/selenium/docs/api/py/common/selenium.common.exceptions.html#module-selenium.common.exceptions

posted @ 2018-05-03 15:37  菜鸟可米  阅读(13485)  评论(0编辑  收藏  举报
jQuery火箭图标返回顶部代码