How to take partial screenshot (frame) with Selenium WebDriver?

SeleniumAutomation TestingTesting Tools

Whenever we encounter a failure during testing, it is a common nature to capture the screenshots wherever there is a deviation from the expected result. Thus it is considered a mandatory step to attach a screenshot for creating a bug.

While automating a bunch of test cases of a considerable number, capturing screenshot is critical to infer why a test case has failed for both the development and testing team. As they debug the failures, going through the screenshot and conclude if the failure is due to script issue or defect in the application.

Sometimes we may need to capture the screenshot of a particular element. Here we have to capture the entire page screenshot then crop that image as per the location and dimension of the element.


Code Implementation.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.Point;
import java.awt.image.BufferedImage;
public class ScrshtElemnt{
   public static void main(String[] args) {
      System.setProperty("", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url ="";
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      // identify logo
      WebElement l=driver.findElement(By.xpath( "//*[@class='top-logo']"));
      // capture screenshot and store the image
      File s = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
      BufferedImage f =;
      //location of webelement
      Point location= l.getLocation();
      // Dimension of element
      int w= l.getSize().getWidth();
      int h=l.getSize().getHeight();
      // Image Crop
      BufferedImage cImage= f.getSubimage(location.getX(), location.getY(),  w, h);
      ImageIO.write(cImage, "png", s);
      FileUtils.copyFile(s, new File("tutorialspointlogo.png"));


Published on 28-Aug-2020 09:56:24