简体   繁体   中英

Selenium in Python: Setting Firefox profile to webdriver does not seem to work

I want to be able to download a file from a website with a Python script by using Selenium. My problem is that creating and setting a Firefox Profile to the Firefox webdriver instance does not seem to work... Here is my code:

 profile = webdriver.FirefoxProfile();

 profile.set_preference("browser.download.folderList", 2);
 profile.set_preference("browser.download.manager.showWhenStarting", False);
 profile.set_preference("browser.download.dir", os.getcwd());
 profile.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/xml");
 profile.update_preferences();

 browser = webdriver.Firefox(firefox_profile=profile);

Even with the settings above, the open/save dialog box still opens up and the download does not happen. I then tried to do something simpler:

profile = webdriver.FireforProfile();

profile.set_preference("browser.startup.homepage", "http://www.google.com");
profile.update_preferences();

browser = webdriver.Firefox(firefox_profile=profile);

And all i get is firefox to open, that's it. This brings me to believe that the profile is not being set to the driver. Any help would be appreciated!

For anyone who comes along this here is a function that will return a webdriver with some common options. It shouldn't have a hardcoded path to the Firefox profile but I haven't gotten around to that yet

def get_firefox_driver(download_dir=None, use_profile=False, headless=False):

    if download_dir is None:
        download_dir = os.getcwd()
    if use_profile:
        try:
            fp = webdriver.FirefoxProfile(r'C:\Users\MDDT0040\AppData\Roaming\Mozilla\Firefox\Profiles\u5jvcbqp.dev-edition-default-1525796820341',)
        except:
            print('cant get profile')
            fp = webdriver.FirefoxProfile()
    else:
        fp = webdriver.FirefoxProfile()

    fp.set_preference("browser.download.folderList", int(2))
    fp.set_preference("browser.download.manager.showWhenStarting", False)
    fp.set_preference("browser.download.manager.showAlertOnComplete", False)
    fp.set_preference("browser.download.dir", download_dir)
    fp.set_preference('browser.helperApps.neverAsk.saveToDisk',
                      "text/csv,text/comma-separated-values,text/comma-separated-values;charset=UTF-8")
    if headless:
        options = Options()
        options.headless = True
        return webdriver.Firefox(firefox_profile=fp, firefox_options=options)
    else:
        return webdriver.Firefox(firefox_profile=fp)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM