TESTEROPS

A pragmatic approach to QA and OPS

Screenshot Of A Specific Element

Being able to take screenshot is a huge plus point in Selenium. I absolutely love this feature. If we use the getScreenshotAs( ) function to take a screenshot, it takes screenshot of full page. In many situations, we just want the screenshot of a particular element.

The approach followed is that we take the screenshot of the full page and then crop it using two dimensions-height and width of the element we want to take the screenshot of.


public class Screenshot {
private String baseUrl;
private WebDriver driver;

@Test
public void f() throws IOException,InterruptedException {
driver.get(baseUrl);

//take screenshot of the page and save it as FILE type
File scrshot=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

//copy it in D:\\
FileUtils.copyFile(scrshot, new File("D:\\screenshot.png"));

//find the specific webelement whom we want the screenshot
WebElement e=driver.findElement(By.xpath("//*[@id='post-22532']/div[1]/div[2]/div/div/p[25]/a/img"));

Point p= e.getLocation();

//get height and width of element
int h=e.getSize().getHeight();
int w=e.getSize().getWidth();

System.out.println(h);
System.out.println(w);

BufferedImage img=ImageIO.read(scrshot);

//crop image using the height and width dimensions
BufferedImage finalImg=img.getSubimage(p.getX(), p.getY(), w, h);

ImageIO.write(finalImg, "png", scrshot);

File f1=new File("D:\\element.png");
FileUtils.copyFile(scrshot, f1);

}
@BeforeTest
public void beforeTest() {
driver= new FirefoxDriver();
baseUrl="http://www.toolsqa.com/selenium-webdriver/headless-browser-testing-selenium-webdriver/";
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

}

@AfterTest
public void afterTest() {
driver.quit();
}

}

Screenshots

This is the element we want the screenshot of

ele

After running the program, we get the screenshot in my D:\\ drive.

ele2

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: