My question is how to capture specific content in a web page to a screen shot but I couldn't. Lets consider any web page and if I'm trying to capture the content of any one class and wants to take a screenshot of just that class in Selenium, How can I do it! Do I need to consider dimensions and if so how do I do that. Please advice me how to do this.
I'm using the below functions in selenium:
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
BufferedImage fullimg = ImageIO.read(screenshot);
Point point = element.getLocation();
int elewidth = element.getSize().getWidth();
int eleheight = element.getSize().getHeight();
BufferedImage elementScreenshot = fullimg.getSubimage(point.getX(), point.getY(),elewidth,
eleheight);
ImageIO.write(elementScreenshot, "png", new File("Path"));
Second function:
Robot robot = new Robot();
Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage screenFullImage = robot.createScreenCapture(screenRect);
ImageIO.write(screenFullImage, "png", new File("Path"));
You need to get the WebElement you want to capture and with FileUtils from Apache you can save it as file.
Apache Common IO: https://mvnrepository.com/artifact/commons-io/commons-io/2.7
WebDriver driver = ...;
try{
driver.get("https://www.google.com/");
WebElement logo = new WebDriverWait(driver, 60).until(
ExpectedConditions.visibilityOfElementLocated(
By.xpath("//div[@id = 'main']")
)
);
File logoFile = logo.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(logoFile, new File("logo.jpg"));
}catch(Exception e){
e.printStackTrace();
}finally{
driver.quit();
}