webDriver提供了截图函数 getScreenshotAs()方法来截取当前窗口
1、这个是简单的调用截图方法
public class baidu3 {
public static void main(String[] args) throws InterruptedException {
System.out.println("开始执行代码");
System.setProperty("webdriver.chrome.driver", "C:\app\chromedriver_win32\chromedriver.exe");
WebDriver webDriver = new ChromeDriver();
webDriver.get("http://www.baidu.com");
Thread.sleep(3000);
webDriver.findElement(By.id("kw")).sendKeys("webdriver api");
webDriver.findElement(By.id("su")).click();
Thread.sleep(3000);
try {
File srcFile = ((TakesScreenshot)webDriver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(srcFile, new File("C:\app\FirstZDH\src\main\java\com\test"));
}catch(Exception e){
e.printStackTrace();
}
Thread.sleep(3000);
webDriver.close();
System.out.println("写完了哈");
}
}
2、以下方法是自己在网上自己找的 很方便的 封装成一个方法,每次使用调用就可以了
/**
- 作用是获取当前屏幕的大小并截图,
- @author 小胖
*/
public class CameraTest {
private static String filePreStr;
private String defName = "cameraImg"; // 默认截图名称
static String serialNum ; //截图名称后面的数字累加
private static String imageFormat; // 图像文件的格式
private String defaultImageFormat = "png"; //截图后缀
static Dimension d = Toolkit.getDefaultToolkit().getScreenSize(); //获取全屏幕的宽高尺寸等数据
public CameraTest() {
filePreStr = defName;
imageFormat = defaultImageFormat;
}
public CameraTest(String s, String format) {
filePreStr = s;
imageFormat = format;
}
public void snapShot() {
try {
// *** 核心代码 *** 拷贝屏幕到一个BufferedImage对象screenshot
BufferedImage screenshot = (new Robot()).createScreenCapture(new Rectangle(0, 0, (int) d.getWidth(), (int) d.getHeight()));
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("MMddHHmmss");
serialNum=sdf.format(d);
String name = filePreStr +serialNum+ "." + imageFormat;
File f = new File(name);
// System.out.println("Save File " + name);
// 将screenshot对象写入图像文件
ImageIO.write(screenshot, imageFormat, f);
// System.out.println("..Finished!\n");
} catch (Exception ex) {
System.out.println(ex);
}
}
// 运行之后,即可将全屏幕截图保存到指定的目录下面<br> // 配合前端页面上面的选择尺寸等逻辑,传到后台,即可实现自由选择截图区域和大小的截图<br>
/* public static void main(String[] args) {
CameraTest cam = new CameraTest("c:\Hello", "png");//
cam.snapShot();
}*/
}
网友评论