user3548850
user3548850

Reputation: 73

how to save screenshot taken from webdriver and save in the project folder?

Project structure

public class ScreenCapture {  

PartyBase partybase = new PartyBase() ;         
public void getscreenshot(String testname) 
{
    Date date = new Date() ;
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss") ;
        File scrFile = ((TakesScreenshot)PartyBase.driver).getScreenshotAs(OutputType.FILE);
     //The below method will save the screen shot in d drive with name "screenshot.png"
        try {
            FileUtils.copyFile(scrFile, new File("BaseApp\\BaseApp\\screenshots\\screenshot_"+testname+"_"+dateFormat.format(date)+".png"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            System.out.println("e::::::::::"+e);
        }
}
}

I am taking screenshots from selenium webdriver and want to save them in my project screenshot folder as shown in the pic . I am unable to do so , please help me what changes are needed to be done in the code .

Upvotes: 0

Views: 7397

Answers (3)

Radadiya Nikunj
Radadiya Nikunj

Reputation: 1085

You can use following code snippet for this.

It will autiomatically create specific folder directory for screen-shot storage.

Folder Directory will be : Year > Month > Day > ScreenShotName_timestamp.png

public class ScreenShotHelper {

    private static ScreenShotHelper instance = null;

    public static ScreenShotHelper getInstance() {
        if (instance == null) {
            instance = new ScreenShotHelper();
        }
        return instance;
    }

    public void takeScreenShot(WebDriver driver, String className) {

        LogLoader.serverLog.trace("In takeScreenShot()");

        try {

            if(driver!=null) {

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

                File screenShotName;

                String strPath = getDatedPath(ConfigLoader.getScreenshotPath());

                screenShotName = new File(strPath + className + BaseConstant.UNDERSCORE_SIGN + System.currentTimeMillis() + BaseConstant.PNG_IMG);

                FileUtils.copyFile(scrFile, screenShotName);

                Reporter.log("<a href='" + screenShotName.getAbsolutePath() + "'> <img src='"+ screenShotName.getAbsolutePath() + "' height='100' width='100'/> </a>");

                LogLoader.serverLog.trace("Screenshot has been successfully stored. [Destination Path : "+screenShotName+"]");

            }

        } catch (IOException e) {
            LogLoader.serverLog.error("Error occurren while taking screenshot for failure testcases. Reason : " + e.getMessage());
            e.printStackTrace();
        }

        LogLoader.serverLog.trace("Out takeScreenShot()");

    }

    protected String getDatedPath(String strPath) {

        LogLoader.serverLog.trace("In getDatedPath()");

        Calendar currentDate = Calendar.getInstance();
        int iYear = currentDate.get(Calendar.YEAR);
        int iMonth = currentDate.get(Calendar.MONTH) + 1;
        int iDay = currentDate.get(Calendar.DAY_OF_MONTH);

        String targetFolder = null;

        if (strPath == null || strPath.length() == 0) {
            return strPath;
        }

        if (!strPath.endsWith(File.separator)) {
            strPath = strPath + File.separator;
        }

        targetFolder = strPath + iYear + File.separator + iMonth + File.separator + iDay + File.separator;

        LogLoader.serverLog.trace("Out getDatedPath()");

        return targetFolder;
    }

}

Upvotes: 0

Zakaria Shahed
Zakaria Shahed

Reputation: 2697

This code work for me, First Create a class CaptureScreenShot

import java.io.File;
        import java.io.IOException;
        import java.text.DateFormat;
        import java.text.SimpleDateFormat;
        import java.util.Date;
        import org.apache.commons.io.FileUtils;
        import org.openqa.selenium.OutputType;
        import org.openqa.selenium.TakesScreenshot;
        import org.openqa.selenium.WebDriver;
        import org.testng.ITestResult;

        public class CaptureScreenShot {
            private static final DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd SSS");

            public static String captureScreen(WebDriver driver, String screenName) throws IOException{

                TakesScreenshot screen = (TakesScreenshot) driver;
                File src = screen.getScreenshotAs(OutputType.FILE);

                String dest ="C:/xampp//htdocs/Automation_report/Test-ScreenShots"+screenName+".png"; //set any path where you want to save screenshot

                File target = new File(dest);
                FileUtils.copyFile(src, target);

                return dest;
            }

            public static String generateFileName(ITestResult result){
                Date date = new Date();
                String fileName = result.getName()+ "_" + dateFormat.format(date);
                return fileName;

            }
        }

This is my After Method

    @AfterMethod
                public void setTestResult(ITestResult result) throws IOException {

                    String screenShot = CaptureScreenShot.captureScreen(driver, CaptureScreenShot.generateFileName(result));

                    if (result.getStatus() == ITestResult.FAILURE) {
                        test.log(Status.FAIL, result.getName());
                        test.log(Status.FAIL,result.getThrowable());
                        test.fail("Screen Shot : " + test.addScreenCaptureFromPath(screenShot));
                    } else if (result.getStatus() == ITestResult.SUCCESS) {
                        test.log(Status.PASS, result.getName());
                        test.pass("Screen Shot : " + test.addScreenCaptureFromPath(screenShot));
                    } else if (result.getStatus() == ITestResult.SKIP) {
                        test.skip("Test Case : " + result.getName() + " has been skipped");
                    }


                    driver.quit();
                }

                }

Hope it will help you

Upvotes: 0

anshul Gupta
anshul Gupta

Reputation: 1270

Below is the code in order to call the screenshot function, ITestResult will get based on your test case pass/failure value :

@AfterMethod
    public void tearDown(ITestResult result)
    {

        if(ITestResult.FAILURE==result.getStatus()) {
            CaptureScreenshots.capturescreen(driver,result.getName(),"FAILURE");
        }
        else {
            CaptureScreenshots.capturescreen(driver,result.getName(),"SUCCESS");
        }
    }
  1. Below is the CaptureScreenshots utility, assuming you have two folders created for a) ScreenshotsFailure b) ScreenshotsSuccess

public class CaptureScreenshots {

            public static void capturescreen(WebDriver driver, String screenShotName, String status)
                {
                    try {
                        TakesScreenshot takesScreenshot = (TakesScreenshot) driver;

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

                        if (status.equals("FAILURE")) {
                            FileUtils.copyFile(scrFile, new File("./ScreenshotsFailure/" + screenShotName + ".png"));
                        }
                        else if(status.equals("SUCCESS"))
                        {
                            FileUtils.copyFile(scrFile, new File("./ScreenshotsSuccess/" + screenShotName + ".png"));
                        }


                        System.out.println("Printing screen shot taken for className "+ screenShotName);

                    }
                    catch (Exception e)
                    {
                        System.out.println("Exception while taking screenshot " + e.getMessage());
                    }

                }
            }

Upvotes: 1

Related Questions