在测试的过程中,很多情况下在我们测试遇到BUG时,或者需要验证某个元素的状态或者显示的数值时,可以将屏幕截取下来进行对比又或者在异常或者错误发生的时候将屏幕截取并保存起来,供后续分析和调试所用,那么在自动化测试过程中当然也是需要这些操作来辅助我们测试的,那么今天我们就来学习一下如何通过selenium来截图保存。
首先今天我们是以截取百度新闻的首页来举例:
第一步:创建一个类为:com.yumeihu.D1
第二步:创建一个java文件为:ScreenShoot
第三步:创建文件夹:ScreenShoots 用来存放截图的文件
package com.yumeihu.D1;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class ScreenShoot {
public static void main(String[] args) throws Exception {
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://www.baidu.com/");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
Thread.sleep(3000);
System.out.println("已经成功进入:"+ driver.getTitle());
driver.findElement(By.xpath(".//*[@id='u1']/a[1]")).click();
//调用截图方法 ,指定了OutputType.FILE做为参数传递给getScreenshotAs()方法,其含义是将截取的屏幕以文件形式返回
File src= ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
// 拷贝截图文件到我们项目./Screenshots,
//FileUtils.copyFile(file1,file2); file1,file2都是文件类型File; 把file1拷贝到file2
FileUtils.copyFile(src, new File(".\\Screenshots\\screen.png"));
System.out.println("已经截图完毕");
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
}
}
运行结果如下:
到此,最简单的截图就完成了
文章参考:https://blog.youkuaiyun.com/u011541946/article/category/6958269/2