如何降低使用硒拍摄的屏幕截图的质量或尺寸?

时间:2016-04-12 14:35:55

标签: ruby selenium selenium-webdriver cucumber

我正在使用Cucumber并行运行一套测试,然后将它们一起分组到一个HTML报告中。在失败的测试中,我的浏览器截图并作为报告中的png嵌入。对于具有大量失败的测试运行,报告可以增长到50MB,并且报告加载需要花费很长时间。

有没有办法截取屏幕截图,缩小屏幕大小,然后才将其嵌入到报告中,以便我可以降低文件大小?假设图像需要嵌入,不能作为与报告分开的文件存储。

1 个答案:

答案 0 :(得分:1)

Selenium没有提供调整屏幕截图大小的方法。但是,您可以轻松覆盖“screenshot_as”方法,使其返回较小的图像。 此示例使用“chunky_png”库将每个屏幕截图的大小调整为原始大小的80%:

require 'selenium-webdriver'
require 'chunky_png'

module Selenium
  module WebDriver
    module DriverExtensions
      module TakesScreenshot

        def screenshot_as(format)

          # take a screenshot and load it with ChunkyPNG
          img = ChunkyPNG::Image.from_blob(bridge.getScreenshot.unpack("m")[0])

          # reduce the size to 80% of the original size
          img = img.resize((img.width * 0.8).floor, (img.height * 0.8).floor)

          case format
            when :base64
              img.to_blob.pack('A*m')
            when :png
              img.to_blob
            else
              raise Error::UnsupportedOperationError, "unsupported format: #{format.inspect}"
          end
        end

      end
    end
  end
end