Saturday 13 October 2018

How to get exact element screenshot captured in Selenium?

How to get exact element screenshot captured in Selenium?


In Selenium, we can capture full screenshot using TakesScreenshot Interface. 

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

screenshot will contain the full screenshot. We could copy that file to any location we want using FileUtils (Apache commons - https://commons.apache.org/). 

File destFile = new File("C:\\Images\\dest.png");
FileUtils.copyFile(screenshot, destFile);


Now to be able to capture exact element screenshot, we need to get dimension of element first. 

let us consider this is the element we have. 

WebElement ele = driver.findElement(By.id("hplogo"));

getLocation() will give us x and y coordinates of element. 
getWidth() and getHeight() will give us width and height of element rectangle respectively. 

// Get the location of element on the page
Point point = ele.getLocation();

// Get width and height of the element
int eleWidth = ele.getSize().getWidth();
int eleHeight = ele.getSize().getHeight();


To capture element screenshot, we need to get portion of image from full screenshot.

// Get entire page screenshot
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
BufferedImage  fullImg = ImageIO.read(screenshot);

Now, fullImg contains, full screenshot.

We can use getSubimage() method to get portion of it as given below:


// Crop the entire page screenshot to get only element screenshot
BufferedImage eleScreenshot= fullImg.getSubimage(point.getX(), point.getY(),
    eleWidth, eleHeight);
ImageIO.write(eleScreenshot, "png", screenshot);

// Copy the element screenshot to disk
File screenshotLocation = new File("C:\\Images\\Test.png");
FileUtils.copyFile(screenshot, screenshotLocation);


This way, we can capture exact element screenshot.

Very Imp Note: If you are working on OS like windows 10, where zoom level is 125% or something, you may not get exact screenshot of element due to zoom level set. So set zoom level to 100% which will give proper screenshot. 


if you have any questions about this do write in comment below. 

Hope this blog has been useful to you. If yes do follow my blogs by entering your email by 
clicking on "Follow" (blue) button. 

You can as well explore my 

Youtube Channel: https://www.youtube.com/user/srinivaskinik

And 

facebook page: https://www.facebook.com/srinivaskinikalmady/

Thank you.

No comments:

Post a Comment

How to schedule RFT (Rational Functional Tester) scripts to run using Jenkins / schedule

How to schedule RFT (Rational Functional Tester) scripts to run using Jenkins / schedule 1. Create a batch file with following content ...