本文介绍了如何使用Selenium Webdriver捕获特定元素而不是整个页面的屏幕截图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当前,我正在尝试使用Selenium WebDriver捕获屏幕截图.但是我只能获取整个页面的屏幕截图.但是,我想要的只是捕获页面的一部分,或者仅捕获基于ID或任何特定元素定位符的特定元素. (例如,我希望捕获图像ID为"Butterfly"的图片)
Currently I'm trying to capture a screenshot using the Selenium WebDriver. But I can only obtain the whole page screen shot. However, what I wanted is just to capture a part of the page or perhaps just on specific element based on ID or any specific element locator. (For example, I wish to capture the picture with image id = "Butterfly")
有什么方法可以按选定的项目或元素来捕获屏幕截图吗?
Is there any way to capture a screenshot by selected item or element?
推荐答案
我们可以通过裁剪整个页面屏幕截图来获得元素屏幕截图,如下所示:
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);
这篇关于如何使用Selenium Webdriver捕获特定元素而不是整个页面的屏幕截图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!