Thursday 20 February 2014

How to take a screenshot of webpage using selenium webdriver in Java?

We can take a screenshot easily using below code. Please note that we need to import below classes/interfaces.

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.OutputType;


Full example in Java to take a screenshot is given below.


package temp;
import java.io.File;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

//import com.sun.jna.platform.FileUtils;


@SuppressWarnings("unused")
public class OpenGoogle {
   
public static void main(String [] arg)
{

System.setProperty("webdriver.chrome.driver", "C:\\Selenuim\\chromedriver2.8.exe");
WebDriver driver =  new ChromeDriver();

try{
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(50,TimeUnit.SECONDS);
//driver.navigate().to("http://www.google.com");

driver.get("http://www.google.com/");

//take a screenshot
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

//save the screenshot in png format on the disk.
FileUtils.copyFile(scrFile, new File("c:\\sagar\\screenshot.png"));

}

catch(Exception e){
       System.out.println("Exception - > " + e.toString());
       }
       finally{
              driver.close();
              driver.quit();
       }
}      //main function ends
      

}//class ends

When any test case fails, we usually take Screenshot at runtime to help us in analysing the executed test cases to find the state of web application when failure occured.

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

No comments:

Post a Comment

Buy Best Selenium Books

Contributors