Saturday 5 April 2014

Selenium WebDriver : How to TakeScreenshot Of WebElement



Selenium WebDriver : How to TakeScreenshot Of WebElement




Every one know that it is possible to take the screenshot of page using Selenium, but most of the people doesn't that there is a possibility for taking the screen of WebElement also....!, you might have a doubt what is the use of taking the screen shot of the element ?

One of the interesting answer is for comparing the images, Surprised.....! but it is possible compare the images using Selenium WebDriver
Here we go.....:)

                   http://qaautomationworld.blogspot.in/

          Selenium WebDriver : How to TakeScreenshot Of WebElement

1. Taking the screen shot of the page. Every selenium automation engineer know it... :)
WebDriver driver = new FirefoxDriver();
driver.get("http://qaautomationworld.blogspot.in/");
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("c:\\qaautomationworld\\qaautomationworld.png"));

2. Taking the screen shot of particular WebElement

    
  •  Grab full-page screenshot
  •  Get WebElement position
  •  Get WebElement dimension
  •  Crop WebElement image from page screenshot
  • Save WebElement image to disk

 WebDriver driver = new FirefoxDriver();
 driver.get("http://qaautomationworld.blogspot.in/");
 WebElement element = driver.findElement(By.xpath("//img[@alt='Selenium WebDriver Tips']"));
 WrapsDriver wrapsDriver = (WrapsDriver) element;
 //Get the entire Screenshot from the driver of passed WebElement
 File screen = ((TakesScreenshot) wrapsDriver.getWrappedDriver()).
 getScreenshotAs(OutputType.FILE);
 //Create an instance of Buffered Image from captured screenshot
 BufferedImage img = ImageIO.read(screen);
 // Get the Width and Height of the WebElement using
 int width = element.getSize().getWidth();
 int height = element.getSize().getHeight();
 //Create a rectangle using Width and Height
 Rectangle rect = new Rectangle(width, height);
 //Get the Location of WebElement in a Point.
 //This will provide X & Y co-ordinates of the WebElement
 Point p = element.getLocation();
 //Create image by for element using its location and size.
 //This will give image data specific to the WebElement
 BufferedImage dest = img.getSubimage(p.getX(), p.getY(), rect.width,
 rect.height);
 //Write back the image data for element in File object
 ImageIO.write(dest, "png", screen);
 
 FileUtils.copyFile(screen, new File("E:\\qaautomationworld\\qaautomationworld.png"));


Do comment if you have any queries on this post

Note: Reference for this post Selenium Testing Tools Cookbook 

No comments:

Post a Comment

:)