且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-09-10 12:10:28

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

We can get the element screenshot by cropping entire page screenshot as below:

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);

推荐文章