This post was most recently updated on June 14th, 2019
For analysis , debugging and reporting it is important to take screenshot in any state of script execution. To achieve this in selenium we need to follow below steps
- Include library import org.openqa.selenium.TakesScreenshot;
- create object and call getScreenshotAs method
- And paste the file into proper location using FileUtils method copyFile.
Type cast the TakesScreenshot Interface:
1 |
<span style="font-size: 16px;">TakesScreenshot screenShot=((TakesScreenshot)driver);</span> |
Call getScreenshotAs method:
1 |
<span style="font-size: 16px;">File SourceFile=screenShot.getScreenshotAs(OutputType.FILE);</span> |
Create new file to store the data:
1 |
<span style="font-size: 16px;">File DestinationFile=new File(FilePath);</span> |
Copy the content of source to destination file:
1 |
<span style="font-size: 16px;">FileUtils.copyFile(SourceFile, DestinationFile);</span> |
Complete code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<span style="font-size: 16px;">package SocietyHive; import java.io.File; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class TakeScreenShot { public static void main(String args[]){ WebDriver driver = new ChromeDriver(); driver.get("http://mundrisoft.com/"); TakesScreenshot screenShot=((TakesScreenshot)driver); File SourceFile=screenShot.getScreenshotAs(OutputType.FILE); File DestinationFile=new File("D:\\Screenshots"); FileUtils.copyFile(SourceFile, DestinationFile); } }</span> |