selenium+java截图功能使用

在做界面自动化时,很需要截图功能,譬如在异常发生时或者验证点失败时,这样可以快速的定位失败原因,但是如果使用界面截图的方式虽然会把这个屏幕截下来,但是缺点在于机器不能睡眠,如果睡下去则会发现截图是黑的;
其实我们可以使用selenium的截图功能,这种方式只会截取网站的部分(如顶部的浏览器输入框之类则不会截取),其优点在于在截图时操作电脑不会影响截图,未登录状态也受影响;
方法如下(driver为实例化webdriver):

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

而后再用commons-io包中的copyFile方法将其保存下来即可(savePath为文件保存路径);

FileUtils.copyFile(f, new File(savePath));

元素截图代码如下:

driver.get("http://www.google.com");
WebElement ele = driver.findElement(By.id("hplogo"));

// Get entire page screenshot
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
BufferedImage  fullImg = ImageIO.read(screenshot);

// Get the location of element on the page
Point point = ele.getLocation();

// Get width and height of the element
int eleWidth = ele.getSize().getWidth();
int eleHeight = ele.getSize().getHeight();

// Crop the entire page screenshot to get only element screenshot
BufferedImage eleScreenshot= fullImg.getSubimage(point.getX(), point.getY(),
    eleWidth, eleHeight);
ImageIO.write(eleScreenshot, "png", screenshot);

// Copy the element screenshot to disk
File screenshotLocation = new File("C:\\images\\GoogleLogo_screenshot.png");
FileUtils.copyFile(screenshot, screenshotLocation);

猜你喜欢

转载自blog.csdn.net/df0128/article/details/80348729