//截屏功能,并以当前时间戳为文件名保存在指定目录下 public void takeScreenShot(){ String dir_name = "screenshot"; //定义一个截图存放的目录名,此处为当前目录的screenshot目录下 //判断目录是否存在 if(!(new File(dir_name).isDirectory())){ //如果不存在则新建目录 new File(dir_name).mkdir(); } SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd-HHmmss"); //格式化当前时间,例如20120406-165210 String time = sdf.format(new Date()); File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); try{ //将截图存放到指定目录,并以当前时间戳作为文件名保存 FileUtils.copyFile(scrFile, new File(dir_name + File.separator + time + ".png")); }catch(IOException e){ e.printStackTrace(); } }
2、使用java提供的接口截图
//获取元素坐标并截图 public void elePosition(WebDriver driver,By location){ String js = "document.getElementById('su').style.border='2px solid red'"; ((JavascriptExecutor)driver).executeScript(js); WebElement ele = driver.findElement(location); Point p = ele.getLocation(); Dimension d = ele.getSize(); System.out.println("x:"+p.x+" y:"+p.y); System.out.println("height:"+d.height+" width:"+d.width); screenshot(p.x,p.y,d.width,d.height); } //截图 public void screenshot(int x,int y,int w,int h){ String dir_name = "screenshot"; //定义一个截图存放的目录名,此处为当前目录的screenshot目录下 //判断目录是否存在 if(!(new File(dir_name).isDirectory())){ //如果不存在则新建目录 new File(dir_name).mkdir(); } SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd-HHmmss"); //格式化当前时间,例如20131016-165210 String time = sdf.format(new Date()); try { //屏幕的分辨率 int width = (int)Toolkit.getDefaultToolkit().getScreenSize().getWidth(); //要截取的宽度 int height = (int)Toolkit.getDefaultToolkit().getScreenSize().getHeight(); //要截取的高度 //System.out.println(width+" "+height); Robot robot = new Robot(); BufferedImage image = robot.createScreenCapture(new Rectangle(width,height)); image = image.getSubimage(x, y, w+100, h+200); ImageIO.write (image, "png" , new File(dir_name + File.separator + time + ".png")); //保存到硬盘 }catch(AWTException e){ e.printStackTrace(); }catch(IOException e){ e.printStackTrace(); } }
以上两种方法都能成功的截取图片,区别在于:
第一种是截取整个浏览器页面
第二种是截取指定x轴、y轴距离以及图片大小
各位测试道友可根据自己实际需求选择方案。