How to Take Screenshot in Selenium WebDriver

Screenshots are essential for bug analysis, During automation results analysis it would be highly helpful. Here we're explaining how to take screenshots using Selenium Webdriver.

TakesScreenshot is a builtin method avilable in Selenium, which helps to take screenshots. When we invoke TakesScreenshot method, then it will convert Webdriver into screenshot.

getScreenshotAs method deals with creation of image file. There are different ways of capturing the image file like Entire page, Current Window, Visible portion etc.

For more details follow this link

Here comes the code for taking screenshot of browser window
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;

public class MyClass {
 
 public static String driverPath = "D:/Technical/chromedriver_win32/";
 public static WebDriver driver;
  
 public static void main(String []args) throws Exception {
    System.out.println("launching chrome browser");
    System.setProperty("webdriver.chrome.driver", driverPath+"chromedriver.exe");
    driver = new ChromeDriver();
    driver.navigate().to("http://google.com");
   
    GetScreenShot(driver,"D://test.png"); }

  
  public static void GetScreenShot(WebDriver webdriver, String fileWithPath)throws Exception {
  
    TakesScreenshot scrShot =((TakesScreenshot)webdriver);
    File SrcFile=scrShot.getScreenshotAs(OutputType.FILE);
    File DestFile=new File(fileWithPath);
    FileUtils.copyFile(SrcFile, DestFile);}
}
Previous Post Next Post