Explore Courses Blog Tutorials Interview Questions
0 votes
in DevOps and Agile by (29.3k 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 (50.2k points)

You can get the element screenshot by cropping the entire page 

You can achieve this by following the code given below


WebElement ele = driver.findElement("hplogo"));

// Get entire page screenshot

File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

BufferedImage  fullImg =;

// 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!

Browse Categories