selenium对浏览器自动截图

对于UI自动化而言,当出现异常的时候,我们需要能够图文并茂的展示出异常的情况。文---就是log日志了 ,图---就是截图了

当用例执行过程中出现异常的时候怎么去截图并保存呢,写点之前的东西,记录一下

from selenium import webdriver
import unittest

class ApitestStudy(unittest.TestCase):
     # 找到浏览器驱动并执行
    def setUp(self):
        self.driver = webdriver.Chrome(executable_path = "F:\Python\Scripts\chromedriver.exe")
     # 执行测试用例
    def test_captureScreenInCurrentWindow(self):
        url = "https://www.baidu.com/"
        self.driver.get(url)
        try:
            result = self.driver.get_screenshot_as_file(r"H:\gjp\异常截图.png")
            print(result)
        except IOError as e:
            print(e)
    def tearDown(self):
             # 退出浏览器
        self.driver.quit()

if __name__ == "__main__":
    unittest.main()

截图结果:

 实现原理:调用 get_screenshot_as_file(“fillname”)方法,实现对浏览器当前打开的页面进行截图操作。并保存在指定路径下的文件中

更多说明:

  1、调用截图函数get_screenshot_as_file() 截图成功后会返回Ture,如果发生了IOError异常,会返回false。函数中传递的存放图片的路径可以是绝对路径也可以是相对路。

  2、当自动化执行过程中,为实现预期结果,可以将页面图片截图保存,方便快速的定位问题,做到图文并茂的去说明问题。

猜你喜欢

转载自www.cnblogs.com/Zhan-W/p/13197996.html