Monday, January 27, 2014

HOW TO TAKE SCREENSHOT USING SELENIUM WEBDRIVER?

  1. import java.io.File;  
  2. import java.io.IOException;  
  3.   
  4. import org.apache.commons.io.FileUtils;  
  5. import org.openqa.selenium.By;  
  6. import org.openqa.selenium.OutputType;  
  7. import org.openqa.selenium.TakesScreenshot;  
  8. import org.openqa.selenium.WebDriver;  
  9. import org.openqa.selenium.firefox.FirefoxDriver;  
  10.   
  11. public class takeScreenshot{  
  12.   
  13.  public static void main(String[] args) {   
  14.   
  15.   WebDriver driver = new FirefoxDriver();  
  16.   
  17.   driver.get("http://helloselenium.blogspot.com");  
  18.   
  19.   File scrFile;  
  20.   scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);  
  21.   try {  
  22.    FileUtils.copyFile(scrFile, new File("C:\\Screenshots\\test.png"));  
  23.   } catch (IOException e) {  
  24.    e.printStackTrace();  
  25.   }  
  26.     
  27.   driver.quit();  
  28.  }  
  29.   
  30. }  


Following code is to initialize the Firefox driver.
  1. WebDriver driver = new FirefoxDriver();  
Following code is to open the hello selenium blog in browser.
  1. driver.get("http://helloselenium.blogspot.com");  
You can also use the following code is to open the hello selenium blog in browser.
  1. driver.navigate().to("http://helloselenium.blogspot.com");  
Following code is to take the screenshot of the current page. In the below code we are storing the taken screenshot as a file.
  1. scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);  
Following code is to save the taken screenshot on a location. "C:\\Screenshots\\" is the path of location and "test.png" is the filename to save the taken screenshot as a file. This code needs exception handling which can be handled using throws or try catch.
  1. FileUtils.copyFile(scrFile, new File("C:\\Screenshots\\test.png"));  
Following code is to quit the Firefox driver.
  1. driver.quit();  
You can also use the following code is to close the Firefox driver.
  1. driver.close();  

No comments:

Post a Comment