检测在 selenium java 中下载的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30726126/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 10:03:55  来源:igfitidea点击:

detecting a file downloaded in selenium java

javaseleniumwebautomationdownload

提问by Avidan

I wrote an automation test in selenium java that detects if the page is redirecting (the automation detects if a new page is opened, the page redirects to other page, a new tab is opened and if an alert window is opened)

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

Now to the problem. one of the redirects i can't find any way to detect is an automatic downloaded file (you enter a website and the website automatically downloads a file without any trigger from the user)

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

p.s.

ps

I know the download process may differ in each browser, I need it to work mainly on chrome

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

Thanks

谢谢

回答by Avidan

My solution in the end was to count the files in the download directory before and after i open the page.

我最终的解决方案是在打开页面之前和之后计算下载目录中的文件。

I'll be glad to know if someone knows a way to find the trigger for the download

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

回答by Fab738

I had the same question and here is what I found somewhere on the Internet (maybe on stackoverflow, I cannot remember). I just added a line to delete the file so that by calling this method at the beginning of my test, I'm making sure the file does not exist anymore when trying to download it again.

我有同样的问题,这是我在互联网上的某个地方找到的(可能是在 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;
  }

You just have to call with this single line: isFileDownloaded("C:\Path\To\Your\Folder", "yourPdfFile.abc");

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

Hope this helps!

希望这可以帮助!

回答by sandeep kumar chittanuri

I am handling a similar condition in my automation.

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

Step1: set the download path in chrome using chrome preference

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

Make sure that there is no file with the expected file name in the folder where you are downloading.

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

Step 2: navigate to the url in chrome, the file will be automatically downloaded to the specified folder.

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

Step 3: check the file existence in the downloaded folder.

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

回答by A.Ezhikov

I used a combined variants from different sources:

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

  1. Override default download folder:

    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. Method body:

    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.
    
  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.
    

回答by AutomatedOwl

I developed a librarywhich is dealing more clearly in such case. You can generate a ChromeOptions object with given download folder and use a one line method call to download a file and verify succession:

我开发了一个,在这种情况下处理得更清楚。您可以使用给定的下载文件夹生成一个 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();
}

回答by Vineel Pellella

This method is working for me successfully

这种方法对我很成功

 /**
     * 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;
                }
            }
    }

回答by vishal kavita rathi

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

----------------every time you need to delete the downloaded file so add this code also---------

----------------每次需要删除下载的文件时,也要添加此代码---------

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

-----Add a method under this code-------

-----在此代码下添加一个方法-------

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

回答by Athar

This is working for me perfectly:

这对我来说非常有效:

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

回答by Rinash

Hope this will help!

希望这会有所帮助!

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