Friday, September 13, 2019

Post#36.Capturing Screenshot in Selenium Part-2 (Capture Screenshot of Web Element)


Take Screenshot of WebElement

Refer the below program to capture the screenshot of a Web Element.

Program to take a screenshot of Web Element.

package pack4;
import java.awt.image.BufferedImage;
import java.io.File;

import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Point;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class WebElementScreenShot {
              public static void main(String[] args) throws Exception {
                             System.setProperty("webdriver.chrome.driver", "D:\\BrowserDrivers\\chromedriver.exe");
                             ChromeDriver driver = new ChromeDriver();
                             driver.manage().window().maximize();
                             driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
                             driver.get("https://www.makemytrip.com/flights");
                             WebElement ele = driver.findElement(By.xpath("//img[@alt='Make My Trip']"));

                             // 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();
                             int xcordinate = point.x;
                             int ycordinate = point.y;
                             // 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(xcordinate, ycordinate,
                                 eleWidth, eleHeight);
                             ImageIO.write(eleScreenshot, "png", screenshot);
                                 //eleWidth, eleHeight);
                             ImageIO.write(eleScreenshot, "png", screenshot);

                             // Copy the element screenshot to disk
                             File screenshotLocation = new File("E:\\mmt_screenshot.png");
                             FileUtils.copyFile(screenshot, screenshotLocation);
                             driver.close();
              }
}

No comments:

Post a Comment