【问题标题】:How to verify that file is downloaded successfully or not in Selenium?如何在 Selenium 中验证该文件是否成功下载?
【发布时间】:2020-12-02 08:50:38
【问题描述】:

我正在使用 Chrome。单击按钮时,它正在“下载”文件夹中下载文件(没有任何下载窗口弹出,否则我也可以尝试使用 AutoIT 工具)。现在我需要验证文件是否下载成功。稍后我需要验证该文件的内容。文件内容应与 GUI 上显示的内容一致。

【问题讨论】:

    标签: selenium selenium-webdriver


    【解决方案1】:

    如果 program.txt 文件存在,以下代码行返回 true 或 false:

          File f = new File("F:\\program.txt"); 
          f.exists();
    

    您可以在自定义预期条件中使用它:## 等待文件下载并呈现

    使用:

    导入 java.io.File;

    在任何页面对象类中定义方法

    public ExpectedCondition<Boolean> filepresent() {
        return new ExpectedCondition<Boolean>() {
            @Override
            public Boolean apply(WebDriver driver) {
                File f = new File("F:\\program.txt"); 
                return f.exists();
            }
            
            @Override
            public String toString() {
              return String.format("file to be present within the time specified");
            }
        };
    }
    

    我们创建了一个自定义的预期条件方法,现在将其用作:

    在测试代码中等待:

    wait.until(pageobject.filepresent());
    

    输出:

    失败:

    通过

    【讨论】:

      【解决方案2】:
      public static boolean isFileDownloaded(String downloadPath, String fileName) {
         File dir = new File(downloadPath);
         File[] dir_contents = dir.listFiles();
      
         if (dir_contents != null) {
             for (File dir_content : dir_contents) {
                  if (dir_content.getName().equals(fileName))
                      return true;
             }
         }
      
         return false;
      }
      

      您应该在此方法中提供您要检查的文件名(是否已下载)以及应该进行下载的路径 要查找您可以使用的下载路径:

      public static String getDownloadsPath() {
      
         String downloadPath = System.getProperty("user.home");
         File file = new File(downloadPath + "/Downloads/");
         return file.getAbsolutePath();
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-16
        • 1970-01-01
        • 1970-01-01
        • 2016-06-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多