JAVA+selenium 截图操作
参考:https://www.cnblogs.com/longronglang/p/11332194.html
执行自动化测试的时候,我们常常会碰到测试执行失败的时候。但是失败我们不能只看执行失败代码,如果有截图的话,就能很明显直观的看到是哪个地方执行失败。
这里介绍两种方法,一种是selenium工具自带的截图方法,一种是通过Robot,自动化执行的时候,建议将浏览器最大化
第一种:selenium之TakesScreenshot
该方法可以只截取自动化运行的浏览器窗口内,不会截取浏览器的操作按钮和系统的任务栏区域
@Test public void screenshot(){ //自己重新封装的访问url方法 to("https://www.baidu.com"); File srcfile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); try { FileUtils.copyFile(srcfile, new File("H:\\12\\takescreen截图.jpg")); } catch (IOException e) { e.printStackTrace(); } }
文件保存以及运行结果:
第二种:通过Robot截图
该方法会截取屏幕内的所有内容,包括系统自带的任务栏以及浏览器的导航栏和操作菜单
@Test public void screenByRobot(){ to("https://www.sohu.com/"); BufferedImage image = null; try { image = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize())); ImageIO.write(image, "jpg", new File("H:\\12\\rebot截图.jpg")); } catch (AWTException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
运行结果查看:
附:
第三种:保存指定元素截图
手动封装一个方法,只需要传递指定页面,页面定位的元素即可。
public class ElementPicture { public static File captureElement(File screenshot, WebElement element){ try { BufferedImage img = ImageIO.read(screenshot); int width = element.getSize().getWidth(); int height = element.getSize().getHeight(); //获取指定元素的坐标 Point point = element.getLocation(); //从元素左上角坐标开始,按照元素的高宽对img进行裁剪为符合需要的图片 BufferedImage dest = img.getSubimage(point.getX(), point.getY(), width, height); ImageIO.write(dest, "png", screenshot); } catch (IOException e) { e.printStackTrace(); } return screenshot; } }
进行使用及查看
driver.get("https://www.baidu.com/"); Thread.sleep(2000); WebElement setting = driver.findElement(By.id("s-usersetting-top")); Actions actions = new Actions(driver); actions.clickAndHold(setting).perform(); driver.findElement(By.linkText("搜索设置")).click(); WebElement xuanxiang = driver.findElement(By.xpath("/html/body/div[1]/div[6]/div")); File src = ((FirefoxDriver) driver).getScreenshotAs(OutputType.FILE); try { FileUtils.copyFile(src, new File("D:\\screenshoot\\result.png")); FileUtils.copyFile(ElementPicture.captureElement(src, xuanxiang), new File("D:\\screenshoot\\test.png")); } catch (IOException e) { e.printStackTrace(); }