捕获失败的测试用例的屏幕截图

时间:2019-01-24 13:09:27

标签: python-3.x unit-testing selenium selenium-webdriver screenshot

如何在Selenium + Python中捕获失败的测试用例的屏幕截图?我可以获取页面的屏幕截图,但是在捕获失败的测试用例的屏幕截图时遇到了困难。

代码:

def test_2new(self):

   driver = self.driver driver.get("google.com") 
   driver.find_element_by_name("q").send_keys("Automation") 
   driver.set_page_load_timeout(10) 
   driver.find_element_by_name("btnK").click() 
   self.assertTrue("something.com" in self.driver.current_url) 
   print("Google Search") 

@classmethod
def tearDownClass(cls): 

    # cls.driver.refresh() 
    time.sleep(5) 
    if sys.exc_info()[0]: 
         cls.driver.save_screenshot(r"C:\Users\ANCP2\sample.png") 

1 个答案:

答案 0 :(得分:1)

您可以这样做:

def test_2new(self):

    driver = self.driver 
    driver.get("google.com")
    driver.set_page_load_timeout(10)
    driver.find_element_by_name("q").send_keys("Automation")  
    driver.find_element_by_name("btnK").click()

    try:

        self.assertTrue("something.com" in self.driver.current_url) 
        print("Google Search!")

    except AssertionError:

        driver.save_screenshot(r"C:\Users\ANCP2\sample.png")

希望对您有帮助!