封装截图方法
/**
* 保存当前屏幕截图-生成的截图会按照截图的先后顺序生成有序的名称
* @param fileName 图片名称,默认为.png格式,图片默认保存在screenShot目录下
*/
public static String saveScreen(String fileName) {
String imageName ;
try {
// 判断是否存在对应目录,不存在的话则创建
File file = new File(TestConfig.SCREEN_SHOT_PATH);
if (!file.exists() || !file.isDirectory()) {
// 没有目录 创建截屏目录
System.out.println("没有screenshot目录,创建目录");
boolean isMkdirSucc = file.mkdir();
if (isMkdirSucc) {
System.out.println("创建screenshot目录成功");
} else {
System.out.println("创建screenshot目录失败");
}
} else {
System.out.println("存在screenshot目录");
}
imageName = TestConfig.SCREEN_SHOT_PATH + File.separator + "_" + fileName + ".png";
driver.saveScreenshot(imageName);
return imageName;
} catch (Exception e) {
// TODO: handle exception
ResultGenerator.fail("截屏异常", "", BaseErrorType.FUNCTION_FAILED);
return null;
}
}
对元素截图
/**
* 元素截图
* @param element
* @param fileName
* @throws InterruptedException
*/
public static String screenForElement(Element element, String fileName) throws Exception {
String filePath = saveScreen(fileName);
File scrFile = new File(filePath);
try {
Point point = new Point();
point.setLocation(element.getOriginX(),element.getOriginY());
double width = element.getWidth();
double height = element.getHeight();
Rectangle rect = new Rectangle((int)width, (int)height);
BufferedImage img = ImageIO.read(scrFile);
BufferedImage dest = img.getSubimage(point.x, point.y, rect.width, rect.height);
ImageIO.write(dest, "png", scrFile);
driver.sleep(1000);
return filePath;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
快去尝试一下吧!