0 votes
1 view
in DevOps and Agile by (30k points)

Currently, I'm trying to capture a screenshot using the Selenium WebDriver. But I can only obtain the whole page screenshot. However, what I wanted is just to capture a part of the page or perhaps just on the 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 the selected item or element?

1 Answer

0 votes
by (51.2k points)

You can get the element screenshot by cropping the entire page 

You can achieve this by following the code given 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);

This code gives you the entire page and it will crop your particular element. Hope this will help you.

If you are interested to learn Selenium on a much deeper level and want to become a professional in the testing domain, check out Intellipaat’s Selenium online training!

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...