【发布时间】:2016-09-21 20:52:00
【问题描述】:
我正在尝试捕获网页上所有元素的屏幕截图,并希望将其存储在我编写了以下代码的磁盘中。
唯一的问题是这段代码只适用于第一次迭代,之后会发生一些意想不到的事情。
List<WebElement> eleId = driver.findElements(By.xpath("//*[@id]")); //fetch all the elements with ID attribute
System.out.println(eleId.size());
for (int i = 0;i < eleId.size();i++) {
// 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 = eleId.get(i).getLocation();
// Get width and height of the element
int eleWidth = eleId.get(i).getSize().getWidth();
int eleHeight = eleId.get(i).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);
// Creating variables name for image to be stores in the disk
String fileName = eleId.get(i).getAttribute("id");
String imageLocation = "D:\\" + fileName + ".png";
// System.out.println(imageLocation);
// Copy the element screenshot to disk
File screenshotLocation = new File(imageLocation);
FileUtils.copyFile(screenshot, screenshotLocation);
System.out.println("Screenshot has been stored.");
}
【问题讨论】:
-
意料之外的事情是什么意思?你的脚本有什么错误吗?
-
它不会抛出任何错误,而是只运行一次迭代。
标签: selenium selenium-webdriver screenshot bufferedimage