小编典典

如何使用Selenium Webdriver捕获特定元素而不是整个页面的屏幕截图?

selenium

目前,我正在尝试使用Selenium
WebDriver捕获屏幕截图。但是我只能获取整个页面的屏幕截图。但是,我想要的只是捕获页面的一部分,或者仅捕获基于ID或任何特定元素定位符的特定元素。(例如,我希望捕获图像ID
=“ Butterfly”的图片)

有什么方法可以按选定的项目或元素捕获屏幕截图?


阅读 465

收藏
2020-06-26

共1个答案

小编典典

我们可以通过裁剪整个页面截图来获得元素截图,如下所示:

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);
2020-06-26