selenium3(java)之屏幕截图操作

selenium提供了截图的功能,分别是接口是TakesScreenshot和类RemoteWebDriver。该功能是在运行测试用例的过程中,需要验证某个元素的状态或者显示的数值时,可以将屏幕截取下来进行对比;或者在异常或者错误发生的时候将屏幕截取并保存起来,供后续分析和调试所用。

下面以百度首页为例学习一下截图功能如何使用。实例代码如下:

package com.qianli.selenium;

import java.io.File;
import java.io.IOException;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
import com.google.common.io.Files;

public class TestScreenshot {

	public static void main(String[] args) {
		//selenium3需要加载firefox的geckodriver.exe
		String path = "C:\Program Files\Mozilla Firefox\geckodriver.exe" ;
		//设置firefox的系统属性
		System.setProperty("webdriver.gecko.driver", path) ;
		WebDriver driver = new FirefoxDriver();
		driver.get("http://www.baidu.com");
		//指定了OutputType.FILE做为参数传递给getScreenshotAs()方法,其含义是将截取的屏幕以文件形式返回。
		//driver需要强制转换为RemoteWebDriver对象,可以通过eclipse提示进行处理
		File scrFile = ((RemoteWebDriver) driver).getScreenshotAs(OutputType.FILE);
		try {
			//利用FileUtils工具类的copy()方法保存getScreenshotAs()返回的文件对象。
			//看到网上有使用File.copyFile()方法,我这里测试的结果需要使用copy()方法
			Files.copy(scrFile, new File("d:\screenfile.png"));
		} catch (IOException e) {
			// 异常处理
			e.printStackTrace();
		}
		driver.quit();
	}
}

 注意: 
  TakesScreenshot接口是依赖于具体的浏览器API操作的,我在谷歌Chrome浏览器做自动化时可用,用Firefox和IE浏览器均报错,换成RemoteWebDriver就没有问题了。

原文地址:https://www.cnblogs.com/laoluoits/p/8465818.html