【问题标题】:detecting a file downloaded in selenium java检测在 selenium java 中下载的文件
【发布时间】:2015-08-23 22:07:30
【问题描述】:

我在 selenium java 中编写了一个自动化测试,检测页面是否正在重定向(自动化检测是否打开了新页面、页面重定向到其他页面、打开了新选项卡以及是否打开了警报窗口)

现在解决问题。 我无法找到任何检测方法的重定向之一是自动下载的文件(您进入网站,网站会自动下载文件而无需用户触发)

附言

我知道每个浏览器的下载过程可能不同, 我需要它主要在 chrome 上工作

谢谢

【问题讨论】:

标签: java selenium web automation download


【解决方案1】:

我最后的解决方法是统计打开页面前后下载目录中的文件。

我很高兴知道是否有人知道找到下载触发器的方法

【讨论】:

    【解决方案2】:

    我有同样的问题,这是我在互联网上某处找到的(可能在 stackoverflow 上,我不记得了)。我刚刚添加了一行来删除文件,以便通过在测试开始时调用此方法,确保在尝试再次下载时该文件不再存在。

      public boolean isFileDownloaded(String downloadPath, String fileName) {
      File dir = new File(downloadPath);
      File[] dirContents = dir.listFiles();
    
      for (int i = 0; i < dirContents.length; i++) {
          if (dirContents[i].getName().equals(fileName)) {
              // File has been found, it can now be deleted:
              dirContents[i].delete();
              return true;
          }
              }
          return false;
      }
    

    你只需要用这一行来调用: isFileDownloaded("C:\Path\To\Your\Folder", "yourPdfFile.abc");

    希望这会有所帮助!

    【讨论】:

      【解决方案3】:

      我在自动化中处理类似的情况。

      Step1:使用 chrome 偏好设置 chrome 中的下载路径

      ChromeOptions options = new ChromeOptions();
      
      HashMap<String, Object> chromePref = new HashMap<>();
      
      chromePref.put("download.default_directory", <Directory to download file>);
      
      options.setExperimentalOption("prefs", chromePref);
      

      确保您下载的文件夹中没有具有预期文件名的文件。

      第二步:导航到chrome中的url,文件会自动下载到指定文件夹。

      第 3 步:检查下载文件夹中的文件是否存在。

      【讨论】:

        【解决方案4】:

        我使用了来自不同来源的组合变体:

        1. 覆盖默认下载文件夹:

          ChromeOptions options = new ChromeOptions();
          HashMap<String, Object> chromePref = new HashMap<>();
          chromePref.put("download.default_directory", System.getProperty("java.io.tmpdir"));
          options.setExperimentalOption("prefs", chromePref);
          WebDriver driver = new ChromeDriver(options);
          
        2. 方法体:

          WebDriverWait wait = new WebDriverWait(driver, 5);
          String tmpFolderPath = System.getProperty("java.io.tmpdir");
          String expectedFileName = "Some_file_name.ext";
          File file = new File(tmpFolderPath + expectedFileName);
          if (file.exists())
              file.delete();
          // Start downloading here.
          wait.until((ExpectedCondition<Boolean>) webDriver -> file.exists());
          // Do what you need.
          

        【讨论】:

        • 我编辑了格式。请注意,如果您有一个紧跟项目符号/编号项目的代码块,则需要多四个缩进空格。
        • @trincot 没有注意到...谢谢!
        【解决方案5】:

        我开发了一个library,在这种情况下处理得更清楚。 您可以使用给定的下载文件夹生成 ChromeOptions 对象,并使用单行方法调用来下​​载文件并验证继承:

        private SeleniumDownloadKPI seleniumDownloadKPI;
        
        @BeforeEach
        void setUpTest() {
            seleniumDownloadKPI =
                 new SeleniumDownloadKPI("/tmp/downloads");
            ChromeOptions chromeOptions =
                    seleniumDownloadKPI.generateDownloadFolderCapability();
            driver = new ChromeDriver(chromeOptions);
        }
        
        @Test
        void downloadAttachTest() throws InterruptedException {
            adamInternetPage.navigateToPage(driver);
            seleniumDownloadKPI.fileDownloadKPI(
                    adamInternetPage.getFileDownloadLink(), "SpeedTest_16MB.dat");
            waitBeforeClosingBrowser();
        }
        

        【讨论】:

          【解决方案6】:

          这个方法对我很有效

           /**
               * This method will wait until the folder is having any downloads
               * @throws InterruptedException 
               */
              public static void waitUntilFileToDownload(String folderLocation) throws InterruptedException {
                  File directory = new File(folderLocation);
                  boolean downloadinFilePresence = false;
                  File[] filesList =null;
                  LOOP:   
                      while(true) {
                          filesList =  directory.listFiles();
                          for (File file : filesList) {
                              downloadinFilePresence = file.getName().contains(".crdownload");
                          }
                          if(downloadinFilePresence) {
                              for(;downloadinFilePresence;) {
                                  sleep(5);
                                  continue LOOP;
                              }
                          }else {
                              break;
                          }
                      }
              }
          

          【讨论】:

            【解决方案7】:
               String downloadPath = "C:\\Users\\Updoer\\Downloads";
               File getLatestFile = getLatestFilefromDir(downloadPath);
               String fileName = getLatestFile.getName();
               Assert.assertTrue(fileName.equals("Inspections.pdf"), "Downloaded file 
               name is not matching with expected file name");
            

            ----------------每次你需要删除下载的文件所以添加 这段代码也---------

               File file = new File("C:\\Users\\Updoer\\Downloads\\Inspections.pdf"); 
               if(file.delete())
                   System.out.println("file deleted");
             System.out.println("file not deleted");
            

            -----在这段代码下添加一个方法------

                private File getLatestFilefromDir(String dirPath){
                File dir = new File(dirPath);
                File[] files = dir.listFiles();
                if (files == null || files.length == 0) {
                    return null;
                }
            
                File lastModifiedFile = files[0];
                for (int i = 1; i < files.length; i++) {
                   if (lastModifiedFile.lastModified() < files[i].lastModified()) {
                       lastModifiedFile = files[i];
                   }
                }
                return lastModifiedFile;
                } 
            

            【讨论】:

              【解决方案8】:

              这对我来说非常有用:

                public static void waitForTheExcelFileToDownload(String fileName, int timeWait)
                              throws IOException, InterruptedException {
                          String downloadPath = getSystemDownloadPath();
                          File dir = new File(downloadPath);
                          File[] dirContents = dir.listFiles();
              
                          for (int i = 0; i < 3; i++) {
                              if (dirContents[i].getName().equalsIgnoreCase(fileName)) {
                                  break;
                              }else {
                                  Thread.sleep(timeWait);
                              }
                          }
                      }
              

              【讨论】:

                【解决方案9】:

                希望这会有所帮助!

                public static Boolean isFileDownloaded(String fileName) {
                        boolean flag = false;
                        //paste your directory path below
                        //eg: C:\\Users\\username\\Downloads
                        String dirPath = ""; 
                        File dir = new File(dirPath);
                        File[] files = dir.listFiles();
                        if (files.length == 0 || files == null) {
                            System.out.println("The directory is empty");
                            flag = false;
                        } else {
                            for (File listFile : files) {
                                if (listFile.getName().contains(fileName)) {
                                    System.out.println(fileName + " is present");
                                    break;
                                }
                                flag = true;
                            }
                        }
                        return flag;
                    }
                

                【讨论】:

                  【解决方案10】:

                  我使用“存在”方法

                  public boolean isFileDownloaded() throws Exception {
                      final int SLEEP_TIME_MILLIS = 1000;
                      File file = new File(filePath);
                      final int timeout = 60* SLEEP_TIME_MILLIS;
                      int timeElapsed = 0;
                      while (timeElapsed<timeout){
                          if (file.exists()) {
                              System.out.println(fileName + " is present");
                              return true;
                          } else {
                              timeElapsed +=SLEEP_TIME_MILLIS;
                              Thread.sleep(SLEEP_TIME_MILLIS);
                          }
                      }
                      return false;
                  }
                  

                  【讨论】:

                    【解决方案11】:

                    脚本执行期间文件下载到当前用户的下载文件夹中。

                    使用以下代码检查并下载文件

                    public void  delte_file(String filename)
                    
                    {
                        String home = System.getProperty("user.home");
                        String file_name = filename;
                        String file_with_location = home + "\\Downloads\\" + file_name;
                        System.out.println("Function Name ===========================" + home + "\\Downloads\\" + file_name);
                        File file = new File(file_with_location);
                        if (file.exists()) {
                            System.out.println(file_with_location + " is present");
                            if (file.delete()) {
                                System.out.println("file deleted");
                            } else {
                                System.out.println("file not deleted");
                            }
                        } else {
                            System.out.println(file_with_location + " is not present");
                        }
                    }
                    

                    使用以下代码检查文件是否存在:

                    public static String  check_file_exist(String filename)
                        {
                            String home = System.getProperty("user.home");
                                String file_name = filename;
                            String file_with_location = home + "\\Downloads\\" + file_name;
                            System.out.println("Function Name ===========================" + home + "\\Downloads\\" + file_name);
                            File file = new File(file_with_location);
                            if (file.exists()) {
                                System.out.println(file_with_location + " is present");
                                String result = "File Present";
                                return result;
                            } else {
                                System.out.println(file_with_location + " is not present");
                                String result = "File not Present";
                                String result1 = result;
                                return result1;
                            }
                        }
                    

                    【讨论】:

                      猜你喜欢
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 2020-07-02
                      • 2018-07-08
                      • 1970-01-01
                      • 2020-03-31
                      相关资源
                      最近更新 更多