How to capture the screenshot of a specific element rather than entire page using Selenium Webdriver?


We can capture the screenshot of a specific element rather than the entire page using Selenium webdriver. There may be requirements in the project where we have to capture the screenshot of a particular webelement.

First of all we shall capture the screenshot of the entire page and then crop it according to the dimension and location of the element. We shall take the help of the TakeScreenShot interface and use its getScreenshotAs method.

Syntax

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

Next store the image in a file [for example, .jpeg, .png].

FileUtils.copyFile(i, new File("<<path of file>>"))

Example

Code Implementation

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.Point;
import java.awt.image.BufferedImage;
public class ElementScreenshot{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.tutorialspoint.com/index.htm");
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify element
      WebElement m=driver.findElement(By.xpath( "//*[@title='Tutorialspoint']"));
      // full page screenshot capture
      File i = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
      BufferedImage fl = ImageIO.read(i);
      //webelement location
      Point point= m.getLocation();
      // webelement dimension
      int wd= m.getSize().getWidth();
      int ht=m.getSize().getHeight();
      // Crop Image to the element
      BufferedImage c= fl.getSubimage(point.getX(), point.getY(), wd, ht);
      ImageIO.write(c, "png", i);
      //copy screenshot to a file inside project folder
      FileUtils.copyFile(i, new File("logo.png"));
      driver.close();
   }
}

Updated on: 26-Oct-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements