【问题标题】:how to save screenshot taken from webdriver and save in the project folder?如何保存从 webdriver 截取的屏幕截图并保存在项目文件夹中?
【发布时间】:2018-02-26 20:48:43
【问题描述】:

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 截取屏幕截图,并希望将它们保存在我的项目截图文件夹中,如图所示。我无法这样做,请帮助我在代码中需要进行哪些更改。

【问题讨论】:

  • 试试FileUtils.copyFile(scrFile, new File("screenshots\\screenshot_"+testname+"_"+dateFormat.format(date)+".png"));。并刷新文件夹`

标签: java selenium screenshot


【解决方案1】:

下面是调用截图函数的代码,ITestResult 将根据你的测试用例通过/失败值得到:

@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 创建了两个文件夹

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

                }
            }

【讨论】:

    【解决方案2】:

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

    希望对你有帮助

    【讨论】:

      【解决方案3】:

      您可以为此使用以下代码 sn-p。

      它会自动创建特定的文件夹目录来存储屏幕截图。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-03-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-03
        相关资源
        最近更新 更多