Below is the Snippet That Can Help in taking Screenshot of the WebElement on the WebPage
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
driver.get("https://www.facebook.com");
driver.manage().window().maximize();
Thread.sleep(6000);
WebElement fbLogo = driver.findElement(By.xpath("//*[contains(@class,'fb_logo')]"));
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
BufferedImage fullImg = ImageIO.read(screenshot);
// Get the location of element on the page
Point point = fbLogo.getLocation();
// Get width and height of the element
int eleWidth = fbLogo.getSize().getWidth();
int eleHeight = fbLogo.getSize().getHeight();
// 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:\\screenshots\\GoogleLogo_screenshot.png");
FileUtils.copyFile(screenshot, screenshotLocation);
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
driver.get("https://www.facebook.com");
driver.manage().window().maximize();
Thread.sleep(6000);
WebElement fbLogo = driver.findElement(By.xpath("//*[contains(@class,'fb_logo')]"));
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
BufferedImage fullImg = ImageIO.read(screenshot);
// Get the location of element on the page
Point point = fbLogo.getLocation();
// Get width and height of the element
int eleWidth = fbLogo.getSize().getWidth();
int eleHeight = fbLogo.getSize().getHeight();
// 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:\\screenshots\\GoogleLogo_screenshot.png");
FileUtils.copyFile(screenshot, screenshotLocation);
Good explanation!
ReplyDeleteThanks Nimesh :)
ReplyDelete