Screenshot using Selenium – User friendly Tech help

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

n

n

n

n

n

n

n

n

Taking Screenshot of nature using Camera

n

nSolution:-We would achieve it using the TakeScreenshot Interface.
n
nSyntax:-
n
n1.Capture Screenshot

n

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

n

nOutputType.FILE:- We have used Interface Output and we have taken the screenshot as “File” type
nwe can also take screenshot as Byte and  base64 data
nExample:-

n

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

n

ngetScreenshotAs:– Method that Captures the screenshot
nsScreenshot:- It holds a temporary  file that will be deleted once the JVM exits. Thus in the next step we would be saving this file.
n
n2.Saving Screenshot by making a copy of this file.
n
nCreating 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
n

n

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

n

Code:-

n

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(); }}

n

nOutput:-
nWe can open the path and observe the created screenshot.
n
nHappy learning 🙂
n
n
nHow to implement highlight in Selenium

Was this article helpful?
YesNo

Similar Posts