How do I automatically download files from a pop up dialog using selenium-python

后端 未结 10 1332
死守一世寂寞
死守一世寂寞 2020-12-16 13:19

I am trying to automatically download files from a pop up dialog using selenium-python.

The firefox popups look like this

相关标签:
10条回答
  • 2020-12-16 14:12

    I've discovered a useful solution that hopefully will help somebody out there.

    You can skip the prompt altogether with firefox if you're starting the download with a click by holding the ALT key.

    from selenium.webdriver.common.keys import Keys
    from selenium.webdriver.common.action_chains import ActionChains
    ...
    profile.set_preference("browser.altClickSave", True)
    ...
    element = driver.find_element_by_xpath("//a")
    ActionChains(driver).key_down(Keys.ALT).click(element).key_up(Keys.ALT).perform()
    

    This should download any file without needing to specify MIME type of anything.

    0 讨论(0)
  • 2020-12-16 14:15

    Based on Amey's answer 1) and of course Yi Zeng's blog (in ruby) quoting Selenium itself doesn’t interact with system-level dialogs like this as well as the documentation, here is the python snippet to resolve the issue

    from selenium import webdriver
    from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
    
    profile = FirefoxProfile()
    profile.set_preference("browser.helperApps.neverAsk.saveToDisk", 'application/pdf')
    driver = webdriver.Firefox(firefox_profile=profile)
    
    driver.get(target_url)
    #specific to target_url
    driver.find_element_by_css_selector('a[title="Click to Download"]').click()
    
    0 讨论(0)
  • 2020-12-16 14:16
    FirefoxProfile fxProfile = new FirefoxProfile();
     fxProfile.SetPreference("browser.download.panel.shown", false);
     fxProfile.SetPreference("browser.helperApps.neverAsk.openFile", "text/csv,application/vnd.ms-excel");
     fxProfile.SetPreference("browser.helperApps.neverAsk.saveToDisk", "text/csv,application/vnd.ms-excel");
     fxProfile.SetPreference("browser.download.folderList", 2); 
     fxProfile.SetPreference("browser.download.dir", "c:\\mydownloads");
     IwebDriver driver = new FirefoxDriver(fxProfile);
    
    0 讨论(0)
  • 2020-12-16 14:18

    In python, but this will work in Java as well because the firefox preferences are a javascript:

    profile.set_preference("browser.download.panel.shown", False)
    profile.set_preference("browser.helperApps.neverAsk.openFile","text/csv,application/vnd.ms-excel")
    profile.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/csv,application/vnd.ms-excel")
    profile.set_preference("browser.download.folderList", 2);
    profile.set_preference("browser.download.dir", "c:\\firefox_downloads\\")
    browser = webdriver.WebDriver(firefox_profile=profile)
    

    this works for CSV files, modify it for whatever filetype you are downloading.

    0 讨论(0)
提交回复
热议问题