Capture screenshot of failed test cases

2019-02-16 00:05发布

问题:

How can I capture a screenshot of the failed test cases in Selenium + Python? I am able to get screenshots of the page but is facing difficulty in capturing screenshots of failed test cases.

Code:

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:

You can do like:

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")

Hope it helps you!