I'm trying to get the screenshot of the "Next" button on the Gmail login page with the below code.
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.gmail.com");
WebElement signupButton= driver.findElement(By.xpath("//div[@id='identifierNext']"));
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
BufferedImage image = ImageIO.read(screenshot);
int width = signupButton.getSize().getWidth();
int height = signupButton.getSize().getHeight();
Rectangle rect = new Rectangle(width, height);
Point p = signupButton.getLocation();
BufferedImage dest = image.getSubimage(p.getX(), p.getY(), width, height);
ImageIO.write(dest, "png", screenshot);
FileUtils.copyFile(screenshot, new File("C:\\Users\\user\\Desktop\\Screenshots\\loginButton.png"));
The screenshot taken was empty. There is no element in the image.
You don't need to do that anymore. In latest versions of Selenium now you can take screen shot of element straight away as the WebElement interface API already has that ability. take a look at below example:
element.getScreenshotAs(OutputType.BYTES)