How to take screenshots on a webpage using Selenium Java

asked 1 year ago

For the test evidence, we need to take a screenshot on the webpage when the automation script is running. The Selenium Webdriver provides the capabilities to take the screenshot. The below code will take screenshot of the webpage 

TakesScreenshot screenShot =((TakesScreenshot)driver);
// Take the screenshot
File src=screenShot.getScreenshotAs(OutputType.FILE);
// Move the file to the path
File dest=new File(System.getProperty("user.dir")+"\\screenshot\\","test1.png");
//Copy the file
FileUtils.copyFile(src, dest);


We can also take the screenshot of a particular portion of the webpage. In the below example, we take the screenshot for the particular web element portion

WebElement ele = driver.findElement(By.xpath("<"));
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
    BufferedImage fullImg =;
    // Get the location 
    Point point = ele.getLocation();
    // Get the width
    int eleWidth = ele.getSize().getWidth();
    // Get the height
    int eleHeight = ele.getSize().getHeight();
    BufferedImage eleScreenshot = fullImg.getSubimage(point.getX(), point.getY(), eleWidth, eleHeight);
    ImageIO.write(eleScreenshot, "png", screenshot);
    String screenShortName="screenShortName"+new Random().nextInt(1000)+".png";
    File screenshotLocation = new File(format(System.getProperty("user.dir")+"\\screenshot\\%s",screenShortName));
    FileUtils.copyFile(screenshot, screenshotLocation);
}catch (Throwable e){