programing tip

Firefox에서 파일 다운로드 대화 상자에 액세스

itbloger 2020. 10. 5. 07:44
반응형

Firefox에서 파일 다운로드 대화 상자에 액세스


Firefox에서 파일 다운로드 대화 상자를 조작 할 수있는 API가 있습니까? (사용자가 직접 시작하는 것이 아니라 사용자가 무언가를 할 때 나타나는 항목에 액세스하고 싶습니다.)

내가하고 싶은 것은 Selenium에서이 대화 상자에 액세스하는 것입니다 (그리고 Selenium "권한 모드"가 크롬 인터페이스에 액세스하기에 충분한 지 여부도 확실하지 않습니다).


내가 아는 한에서는 아니다. 그러나 Firefox가 자동으로 다운로드를 시작하고 특정 위치에 파일저장 하도록 구성 할 수 있습니다 . 그러면 테스트에서 파일이 실제로 도착했는지 확인할 수 있습니다.


이 문제에 대한 해결책이 있습니다. 코드를 확인하십시오.

FirefoxProfile firefoxProfile = new FirefoxProfile();

firefoxProfile.setPreference("browser.download.folderList",2);
firefoxProfile.setPreference("browser.download.manager.showWhenStarting",false);
firefoxProfile.setPreference("browser.download.dir","c:\\downloads");
firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk","text/csv");

WebDriver driver = new FirefoxDriver(firefoxProfile);//new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capability);

driver.navigate().to("http://www.myfile.com/hey.csv");

나는 같은 문제에 시달렸지만 해결책을 찾았습니다. 나는이 블로그 와 같은 방식으로 했다.

물론 이것은 Java였으며 Python으로 번역했습니다.

fp = webdriver.FirefoxProfile()

fp.set_preference("browser.download.folderList",2)
fp.set_preference("browser.download.manager.showWhenStarting",False)
fp.set_preference("browser.download.dir",getcwd())
fp.set_preference("browser.helperApps.neverAsk.saveToDisk","text/csv")

browser = webdriver.Firefox(firefox_profile=fp)

내 예에서는 CSV 파일이었습니다. 그러나 더 많은 것을 필요로 할 때~/.mozilla/$USER_PROFILE/mimeTypes.rdf


웹 애플리케이션은 3 가지 유형의 팝업을 생성합니다. 즉,

 1| JavaScript PopUps
 2| Browser PopUps
 3| Native OS PopUps [e.g., Windows Popup like Upload/Download]

일반적으로 JavaScript 팝업은 웹 애플리케이션 코드에 의해 생성됩니다. Selenium은 이러한 자바 스크립트 팝업을 처리하기위한 API를 제공합니다 Alert.

결국 브라우저 팝업을 무시하고 파일을 다운로드하는 가장 간단한 방법은 브라우저 프로필을 사용하는 것입니다. 이를 수행하는 몇 가지 방법이 있습니다.

  • 브라우저 속성 (또는)의 변경을 수동으로 포함
  • 프로필 setPreference를 사용하여 브라우저 속성 사용자 지정

방법 1

브라우저 프로필에서 팝업 작업을 시작하기 전에 다운로드 옵션이 기본적으로 파일 저장으로 설정되어 있는지 확인하십시오.

(Firefox 열기) 도구> 옵션> 애플리케이션

여기에 이미지 설명 입력

방법 2

아래 스 니펫을 사용하고 필요할 때마다 편집하십시오.

FirefoxProfile profile = new FirefoxProfile();

String path = "C:\\Test\\";
profile.setPreference("browser.download.folderList", 2);
profile.setPreference("browser.download.dir", path);
profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/msword, application/csv, application/ris, text/csv, image/png, application/pdf, text/html, text/plain, application/zip, application/x-zip, application/x-zip-compressed, application/download, application/octet-stream");
profile.setPreference("browser.download.manager.showWhenStarting", false);
profile.setPreference("browser.download.manager.focusWhenStarting", false);  
profile.setPreference("browser.download.useDownloadDir", true);
profile.setPreference("browser.helperApps.alwaysAsk.force", false);
profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
profile.setPreference("browser.download.manager.closeWhenDone", true);
profile.setPreference("browser.download.manager.showAlertOnComplete", false);
profile.setPreference("browser.download.manager.useWindow", false);
profile.setPreference("services.sync.prefs.sync.browser.download.manager.showWhenStarting", false);
profile.setPreference("pdfjs.disabled", true);

driver = new FirefoxDriver(profile);

나는 같은 문제에 직면했다. 애플리케이션에서 FireFox의 인스턴스는 다음과 같이 DesiredCapabilities를 전달하여 생성되었습니다.

driver = new FirefoxDriver(capabilities);

다른 사람의 제안에 따라 변경했습니다.

FirefoxProfile firefoxProfile = new FirefoxProfile();     
firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk",
    "application/octet-stream");
driver = new FirefoxDrvier(firefoxProfile);

이것은 목적을 달성했지만 불행히도 다른 자동화 테스트가 실패하기 시작했습니다. 그 이유는 이전에 전달 된 기능을 제거했기 때문입니다.

인터넷에서 좀 더 검색하고 다른 방법을 찾았습니다. 원하는 기능에서 프로파일 자체를 설정할 수 있습니다.

따라서 새로운 작업 코드는 다음과 같습니다.

DesiredCapabilities capabilities = DesiredCapabilities.firefox();

// add more capabilities as per your need.
FirefoxProfile firefoxProfile = new FirefoxProfile();        
firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk",
    "application/octet-stream");

// set the firefoxprofile as a capability
capabilities.setCapability(FirefoxDriver.PROFILE, firefoxProfile);
driver = new FirefoxDriver(capabilities);

모르겠지만 Firefox 다운로드 애드온 중 하나의 소스를 확인할 수 있습니다.

다음은 Download Statusbar를 사용하는 소스입니다 .


Most browsers (in mine case Firefox) select the OK button by default. So I managed to solve this by using the following code. It basically presses enter for you and the file is downloaded.

Robot robot = new Robot();

// A short pause, just to be sure that OK is selected
Thread.sleep(3000);

robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);

I had the same problem, I wanted no access of Save Dialogue.

Below code can help:

    FirefoxProfile fp = new FirefoxProfile();
    fp.setPreference("browser.download.folderList",2);
    fp.setPreference("browser.download.manager.showWhenStarting",false);
    fp.setPreference("browser.helperApps.alwaysAsk.force", false);
    // Below you have to set the content-type of downloading file(I have set simple CSV file)
    fp.setPreference("browser.helperApps.neverAsk.saveToDisk","text/csv");

According to the file type which is being downloaded, You need to specify content types.

You can specify multiple content-types separated with ' ; '

e.g:

    fp.setPreference("browser.helperApps.neverAsk.saveToDisk","text/csv;application/vnd.ms-excel;application/msword");

Instead of triggering the native file-download dialog like so:

By DOWNLOAD_ANCHOR = By.partialLinkText("download");
driver.findElement(DOWNLOAD_ANCHOR).click();

I usually do this instead, to bypass the native File Download dialog. This way it works on ALL browsers:

String downloadURL = driver.findElement(DOWNLOAD_ANCHOR).getAttribute("href");
File downloadedFile = getFileFromURL(downloadURL);

This just requires that you implement method getFileFromURL that uses Apache HttpClient to download a file and return a File reference to you.

Similarly, if you happen to be using Selenide, it works the same way using the built-in download() function for handling file downloads.


I didnt unserstood your objective, Do you wanted your test to automatically download file when test is getting executed, if yes, then You need to use custom Firefox profile in your test execution.

In the custom profile, for first time execute test manually and if download dialog comes, the set it Save it to Disk, also check Always perform this action checkbox which will ensure that file automatically get downloaded next time you run your test.


In addition you can add

      profile.setPreference("browser.download.panel.shown",false);

To remove the downloaded file list that gets shown by default and covers up part of the web page.

My total settings are:

        DesiredCapabilities dc = DesiredCapabilities.firefox();
        dc.merge(capabillities);
        FirefoxProfile profile = new FirefoxProfile();
        profile.setAcceptUntrustedCertificates(true);
        profile.setPreference("browser.download.folderList", 4);
        profile.setPreference("browser.download.dir", TestConstants.downloadDir.getAbsolutePath());
        profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
        profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/msword, application/csv, application/ris, text/csv, data:image/png, image/png, application/pdf, text/html, text/plain, application/zip, application/x-zip, application/x-zip-compressed, application/download, application/octet-stream");
        profile.setPreference("browser.download.manager.showWhenStarting", false);
        profile.setPreference("browser.download.manager.focusWhenStarting", false);
        profile.setPreference("browser.download.useDownloadDir", true);
        profile.setPreference("browser.helperApps.alwaysAsk.force", false);
        profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
        profile.setPreference("browser.download.manager.closeWhenDone", true);
        profile.setPreference("browser.download.manager.showAlertOnComplete", false);
        profile.setPreference("browser.download.manager.useWindow", false);
        profile.setPreference("browser.download.panel.shown",false);
        dc.setCapability(FirefoxDriver.PROFILE, profile);
        this.driver = new FirefoxDriver(dc);

참고 URL : https://stackoverflow.com/questions/1176348/access-to-file-download-dialog-in-firefox

반응형