Saturday, 20 December 2014

Screenshot - specific element

Let's see how a screenshot of a specfic element can be taken.

Scenario :

Launch www.babyoye.com and capture screenshot of the element "READ MORE" available at the bottom of the page and save it in .jpg format .


This is how it's done,

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Point;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class ScrDemo3 {

public static void main(String[] args) throws IOException {

System.setProperty("webdriver.ie.driver", "D:\\IEDriverServer.exe");

WebDriver driver = new InternetExplorerDriver();

driver.navigate().to("http://www.babyoye.com/c/Cribs-&-Cradles");

WebElement we = driver.findElement(By.linkText("READ MORE"));

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

BufferedImage img = ImageIO.read(srcFile);

Dimension d = we.getSize();

int width = d.getWidth();

int height = d.getHeight();

Point p = we.getLocation();

int x = p.getX();

int y = p.getY();

BufferedImage eleScreenshot = img.getSubimage(x, y, width, height);

ImageIO.write(eleScreenshot, "jpg", srcFile);

FileUtils.copyFile(srcFile, new File(System.getProperty("user.dir")
+ "\\Screenshot\\ElementScr.jpg"));

System.out.println("Screenshot captured");

driver.quit();
}

}

The screenshot taken is :



Pay It Forward...

Lots of energy ..

DR

No comments:

Post a Comment