如何保存从 webdriver 截取的屏幕截图并保存在项目文件夹中?

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

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

我正在从 selenium webdriver 截取屏幕截图,并希望将它们保存在我的项目屏幕截图文件夹中,如图所示。我无法这样做,请帮助我需要在代码中进行哪些更改。

下面是调用截图功能的代码,ITestResult 会根据你的测试用例得到 pass/failure 值:

@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. 下面是 CaptureScreenshots 实用程序,假设您为 a) ScreenshotsFailure b) ScreenshotsSuccess 创建了两个文件夹

public class 截图 {

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

                }
            }

这段代码对我有用, 首先创建一个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;

            }
        }

这是我的After 方法

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

                }

希望对您有所帮助

您可以为此使用以下代码片段。

它会自动创建特定的文件夹目录用于screen-shot存储。

文件夹目录将是:年 > 月 > 日 > 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;
    }

}