How to Capture Screen Shot in Selenium
Why taking a screenshot?
- Screenshot helps to understand the flow of the Application
- For the failed cases screenshot helps to understand on which page the Test case has failed
- Screenshot is taken to track the execution of Test Cases
The following code will takes the screenshot of the Facebook login page
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
public class screenshot {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
WebDriver a = new FirefoxDriver();
a.manage().window().maximize();
a.get("https://www.facebook.com");
a.findElement(By.xpath(".//*[@id='email']")).sendKeys("learn Automation");
TakesScreenshot ts = (TakesScreenshot)a;
File Source = ts.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(Source, new File("./screenshot/facebook1234.png"));
a.quit();
}
}
1- TakesScreenshot is an interface in selenium and we cannot create a object of interface so we have typecast it
2-Typecasting of TakesScreenshot is done in order to get the object
3-getScreenshotAs is a method which is used to get screen shot as a file/Bytes
4-File is a class in java and its object "source" is used to store the screenshot in buffer memory
5-Again FileUtils is a class in java by which we can use a method called copy file which is used to copy a file stored in buffer memory to a particular project location
6- "./screenshot/facebook.png" :- Here "./" refers to the current project location folder which is Learn Automation
Output
In order to see facebook.pngfile we need to refresh the Learn Automation Project
0 comments:
Post a Comment