Python 2.7 + Selenium 3.8 + Firefox 57 + MacOS Sierra:设置" browser.helperApps.neverAsk.openFile"

时间:2018-01-02 12:32:15

标签: python selenium webdriver

我在使用Selenium 3.8,Firefox 57和Python 2.7从网页下载PDF文件时遇到了困难。如果我没有从"手动更改Firefox配置文件下载设置,请始终询问您保存文件的位置"到特定位置,仍会出现下载弹出框,文件不会自动下载到指定文件夹。

我已经查看了this StackO帖子,我不确定我错过了什么。我是否需要安装和设置木偶?我确实已经设置了geckodriver可执行文件。

这是我的代码:

profile = webdriver.FirefoxProfile("/Users/USERNAME/Library/Application Support/Firefox/Profiles/NAME")
profile.set_preference('browser.download.folderList', 2) # custom location
profile.set_preference('browser.download.manager.showWhenStarting', False)
profile.set_preference("browser.helperApps.neverAsk.openFile", 'application/pdf')
profile.set_preference('browser.helperApps.neverAsk.saveToDisk', 'application/pdf')
profile.set_preference('browser.download.dir', download_to_location)
browser = webdriver.Firefox(profile)
download_to_location = "PATH_TO_FOLDER_WITHIN_DIRECTORY"

for race in races:
        browser.get(race)
        try:
            [browser.find_element_by_xpath(lxp).click() for lxp in download_from_xpaths]
        except: 
            pass

截图: enter image description here

1 个答案:

答案 0 :(得分:0)

要自动将PDF文件下载到指定的文件夹,您可以使用以下代码块:

newpath = "PATH_TO_FOLDER_WITHIN_DIRECTORY"
if not os.path.exists(newpath):
    os.makedirs(newpath) 
profile = webdriver.FirefoxProfile("/Users/USERNAME/Library/Application Support/Firefox/Profiles/NAME")
profile.set_preference("browser.download.dir",newpath);
profile.set_preference("browser.download.folderList",2);
profile.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/plain,application/octet-stream,application/pdf,application/x-pdf,application/vnd.pdf");
profile.set_preference("browser.download.manager.showWhenStarting",False);
profile.set_preference("browser.helperApps.neverAsk.openFile","text/plain,application/octet-stream,application/pdf,application/x-pdf,application/vnd.pdf");
profile.set_preference("browser.helperApps.alwaysAsk.force", False);
profile.set_preference("browser.download.manager.useWindow", False);
profile.set_preference("browser.download.manager.focusWhenStarting", False);
profile.set_preference("browser.helperApps.neverAsk.openFile", "");
profile.set_preference("browser.download.manager.alertOnEXEOpen", False);
profile.set_preference("browser.download.manager.showAlertOnComplete", False);
profile.set_preference("browser.download.manager.closeWhenDone", True);
profile.set_preference("pdfjs.disabled", True);
browser = webdriver.Firefox(profile)
browser.get('Provide_URL_here')