Python为Selenium设置Firefox首选项 - 下载位置

时间:2017-01-13 22:23:32

标签: python selenium web-scraping geckodriver firefox-marionette

我使用Selenium Marrionette和GeckoDriver来提取网络数据。我使用以下命令设置我的Firefox配置文件首选项:

fp = webdriver.FirefoxProfile()
fp.set_preference("browser.download.folderList", 1)
fp.set_preference("browser.helperApps.alwaysAsk.force", False)
fp.set_preference("browser.download.manager.showWhenStarting",False)
fp.set_preference("browser.download.dir", "H:\Downloads")
fp.set_preference("browser.download.downloadDir","H:\Downloads")
fp.set_preference("browser.download.defaultFolder","H:\Downloads")

binary = FirefoxBinary(r'C:\Program Files (x86)\Mozilla Firefox\Firefox.exe')

firefox_capabilities = DesiredCapabilities.FIREFOX
firefox_capabilities['marionette'] = True

driver = webdriver.Firefox(capabilities=firefox_capabilities, firefox_binary=binary, firefox_profile = fp)

根据我在阅读Unable to set firefox profile preferencesFirefoxProfile passed to FirefoxDriver后的理解,现在使用firefox_profile时似乎没有做任何事情。所以我需要实现firefox_capabilities的新更新,但我不确定如何做到这一点。有什么想法吗?

3 个答案:

答案 0 :(得分:7)

好的,我相信我终于搞清楚这个烂摊子了。我没有使用上面的代码,而是使用了以下代码,我指向我的Firefox配置文件夹(如果您需要更新默认配置文件设置,请在运行此代码之前在Firefox中执行此操作):

from selenium.webdriver.firefox.options import Options
binary = FirefoxBinary(r'C:\Program Files (x86)\Mozilla Firefox\Firefox.exe')
fp = (r'C:\Users\username\AppData\Roaming\Mozilla\Firefox\Profiles\oqmqnsih.default')
opts = Options()
opts.profile = fp
firefox_capabilities = DesiredCapabilities.FIREFOX
firefox_capabilities['marionette'] = True
driver = webdriver.Firefox(capabilities=firefox_capabilities,firefox_binary=binary, firefox_options = opts)

我将此代码与我的网页抓取代码一起运行,一旦我点击“导出CSV”链接,它就会自动下载而不是弹出下载管理器窗口。随意添加任何反馈。

答案 1 :(得分:2)

初始代码是正确的。您必须将browser.download.folderList值设置为2:

fp = webdriver.FirefoxProfile()
fp.set_preference("browser.download.folderList", 2) # 0 means to download to the desktop, 1 means to download to the default "Downloads" directory, 2 means to use the directory 
fp.set_preference("browser.helperApps.alwaysAsk.force", False) fp.set_preference("browser.download.manager.showWhenStarting",False) fp.set_preference("browser.download.dir", "H:\Downloads") 

binary = FirefoxBinary(r'C:\Program Files (x86)\Mozilla Firefox\Firefox.exe')

firefox_capabilities = DesiredCapabilities.FIREFOX
firefox_capabilities['marionette'] = True

driver = webdriver.Firefox(capabilities=firefox_capabilities,firefox_binary=binary, firefox_profile = fp)

答案 2 :(得分:1)

您可以 右键单击 ,然后选择 另存为 ,而不是之前的答案,并将其保存到所需的目录,在该点之后,该目录将成为该会话的默认目录,您可以使用相同的方法更改它。但是,如果您希望该路径是动态的并且在同一会话中以编程方式更改它,那么这个也不是解决方案。所以问题的答案是here。如果您可以使用Chrome驱动程序,请按照this answer

中的说明操作