detecting a file downloaded in selenium java

南笙酒味 提交于 2021-02-18 12:09:23

问题


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)

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.

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

Thanks


回答1:


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.

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

Hope this helps!




回答2:


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




回答3:


I am handling a similar condition in my automation.

Step1: set the download path in chrome using chrome preference

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.

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




回答4:


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



回答5:


I used "exists" method

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



回答6:


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.
    



回答7:


I developed a library which 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:

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



回答8:


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



回答9:


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



回答10:


during the script execution file download in the download folder of the current user.

Use the Below code to check and download the file

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

To check file exist or not use the below code:

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



回答11:


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


来源:https://stackoverflow.com/questions/30726126/detecting-a-file-downloaded-in-selenium-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!