Categories
Uncategorized

Screenshot using Selenium

Scenario:-How we can capture error Screenshot while working with Selenium?

Taking Screenshot using PhotoCamera
Taking Screenshot of nature using Camera


Solution:-
We would achieve it using the TakeScreenshot Interface.

Syntax:-


1.Capture Screenshot

File sScreenShot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);


OutputType.FILE:- We have used Interface Output and we have taken the screenshot as “File” type

we can also take screenshot as Byte and  base64 data
Example:-

String screenshotBase64 = ((TakesScreenshot)driver).getScreenshotAs(OutputType.base64);


getScreenshotAs:– Method that Captures the screenshot
sScreenshot:- It holds a temporary  file that will be deleted once the JVM exits. Thus in the next step we would be saving this file.

2.Saving Screenshot by making a copy of this file.


Creating the Copy of Screenshot file and Saving it on required destination path and with given name.
For this we have used copyFile(source,target) method of the FileUtils class

FileUtils.copyFile(sScreenShot, new File("E:\screenshot.jpg"))


Code:-

import java.io.File;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.Test;

public class ScreenShot {
private static WebDriver driver;
@Test
public void launch() throws Exception {
//Luanch browser
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://www.uftHelp.com");
//Making the code to fail
try{
driver.findElement(By.id("uftHelp")).sendKeys("Selenium");
}
catch (Exception e){
//Capture Screenshot on error.
ScreenShot();
}
}

//Function to capture Screenshot
public void ScreenShot() throws Exception
{
//Taking the Screenshot
File sScreenShot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
//Saving the Screenshot
FileUtils.copyFile(sScreenShot,new File("E:\screenshot.jpg"));

}

@AfterTest
public void afterTest() {
//Closing the browser
driver.quit();
}
}


Output:-

We can open the path and observe the created screenshot.

Happy learning 🙂



How to implement highlight in Selenium

3 replies on “Screenshot using Selenium”

Webdriver interface doesnot contains the getscreenshotas method, so we need to typecast webdriver to TakeScreenshot interface to implement the method.

Leave a Reply

Your email address will not be published. Required fields are marked *