Sunday 31 July 2016

Capture Screenshot of required element using Selenium


Usually, the selenium tests would capture the complete screenshot of the application. Capturing multiple screens would increase the size of reports or at times it is unnecessary to capture whole screen.

Ever thought of capturing only required web element?
Yes! we can. Follow the below process to capture the required element.

//Find the web element
WebElement elm = driver.findElement(xpath or any locator);
File compFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
BufferedImage image = ImageIO.read(compFile);

//get the image location & save to a file.
Point pnt = elm.getLocation();
BufferedImage elmImg = image.getSubimage(pnt.getX(), pnt.getY(), elm.getSize().getWidth(), elm.getSize().getHeight());
ImageIO.write(elmImg, "png", compFile);

FileUtils.copyFile(compFile, new File("filepath/filename" + ".png"));

No comments:

Post a Comment