selenium常用的API(一)截屏

 

我们在使用selenium测试过程中,可使用截屏功能将用例执行失败的画面截图保存,方便测试执行结束后查看并定位问题。

以下介绍两种截屏方法:

对当前浏览器窗口截屏

使用selenium自带的get_screenshot_as_file()方法

截图成功后返回True,如果发生了IOError异常,会返回False。

# encoding=utf-8
import unittest
import time
from selenium import webdriver


class VisitSogouByIE(unittest.TestCase):
    def setUp(self):
        # 启动IE浏览器
        #self.driver=webdriver.Firefox(executable_path="e:\geckodriver")
        self.driver = webdriver.Ie(executable_path="d:\driverIEDriverServer")

    def test_captureScreenInCurrentWindow(self):
        url = "http://www.sohu.com"
        # 访问搜狐首页
        self.driver.get(url)
        try:
            '''
            调用get_screenshot_as_file(filename)方法,对浏览器当前打开页面
            进行截图,并保为G盘下的screenPicture.png文件。
            '''
            result=self.driver.get_screenshot_as_file(r"g:screenPicture.png")
            print result
        except IOError, e:
            print e


    def tearDown(self):
        # 退出IE浏览器
        self.driver.quit()


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

使用PIL模块调用操作系统API截桌面全屏

PIL:Python Imaging Library,已经是Python平台事实上的图像处理标准库了。PIL功能非常强大,但API却非常简单易用。

PIL非python内置模块,使用前需先安装PIL安装包→ pip install PIL

from PIL import ImageGrab
im=ImageGrab.grab()
im.save("1.jpg","jpeg")

要想了解PIL的更多使用,参请见:https://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/00140767171357714f87a053a824ffd811d98a83b58ec13000

原文地址:https://www.cnblogs.com/zeke-python-road/p/9320903.html