问题场景:有时当我们的脚本运行报错时,需要通过截屏来分析异常的来源。
而selenium也提供了可以截图的方法TakesScreenshot.getScreenshotAs

举例:我们把截屏的图片存储在D盘AutoScreenCapture文件夹下,为了好区分截图,每张截图的命名都取当前时间,脚本可以这么写

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
private WebDriver driver;
//调用方法
takeScreenShot(driver);
-----------------------------------------------------------------
//方法体
public static void takeScreenShot(WebDriver driver)
{
File screenShotFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(screenShotFile, new File("D:\\AutoScreenCapture\\" + getCurrentDateTime()+ ".jpg"));
}
catch (IOException e) {e.printStackTrace();}
}
public static String getCurrentDateTime(){
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd_HHmmss");//设置日期格式
return df.format(new Date());
}