0

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"));
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • Have you tried `WebElement welem = ...;` -> `File scrFile = welem.getScreenshotAs(OutputType.FILE);` and using `FileUtils` from `Apache Common IO` save the file. – KunLun Jun 12 '20 at 17:02
  • I'm able to take screenshot of complete web page but I want to capture only specific content. That's where I got stuck – Chandu Sanaka Jun 12 '20 at 17:14
  • Read my answer and let's me know if it helps. – KunLun Jun 12 '20 at 17:15

1 Answers1

0

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();
}
KunLun
  • 3,109
  • 3
  • 18
  • 65