如何使用Python Selenium加载Firefox配置文件?

21
我希望您能够在我Windows机器上使用Python Selenium。 我已经升级了Firefox,Selenium和Geckodriver的最新版本,但我仍然收到以下错误消息:
Python脚本
from selenium import webdriver
driver = webdriver.Firefox()

错误提示
Traceback (most recent call last):
  File "run.py", line 17605, in <module>
  File "<string>", line 21, in <module>
  File "site-packages\selenium\webdriver\firefox\webdriver.py", line 77, in __init__
  File "site-packages\selenium\webdriver\firefox\extension_connection.py", line 49, in __init__
  File "site-packages\selenium\webdriver\firefox\firefox_binary.py", line 68, in launch_browser
  File "site-packages\selenium\webdriver\firefox\firefox_binary.py", line 103, in _wait_until_connectable
WebDriverException: Message: Can't load the profile. Profile Dir: %s If you specified a log_file in the FirefoxBinary constructor, check it for details.

我也尝试使用以下代码创建Firefox配置文件:
from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary

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/vnd.ms-excel'))
profile.set_preference('general.warnOnAboutConfig', False)

gecko_path = "path_to_geckodriver\\geckodriver.exe"
path = "path_to_firefoxs\\Mozilla Firefox\\firefox.exe"
binary = FirefoxBinary(path)
driver = webdriver.Firefox(firefox_profile=profile,executable_path=gecko_path)
  • Python 2.7
  • Firefox 60
  • Geckodriver-v0.20.1-win64.zip
  • Selenium 3.12.0
Python 2.7 火狐浏览器 60 Geckodriver-v0.20.1-win64.zip Selenium 3.12.0

5个回答

18

解决方案:

from selenium import webdriver
fp = webdriver.FirefoxProfile('/home/gabriel/.mozilla/firefox/whatever.selenium')
driver = webdriver.Firefox(fp)

在我找到这个问题之前,我一直很苦恼。尽管现在已经得到了解决,但它对我很有帮助,因为它展示了一些命令。

第一个版本不起作用,因为之后我无法通过selenium连接:

from selenium.webdriver.firefox.options import Options
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

options = Options()
options.add_argument("-profile")
options.add_argument("/home/gabriel/.mozilla/firefox/whatever.selenium")
firefox_capabilities = DesiredCapabilities.FIREFOX
firefox_capabilities['marionette'] = True
driver = webdriver.Firefox(capabilities=firefox_capabilities, firefox_options=options)

我确信这个代码加载了"profile:selenium",因为如果我进入关于:profiles页面,我可以看到:

配置文件:selenium 这是正在使用的配置文件,无法删除。

即使"whatever.selenium"不是我的系统上默认的配置文件。

备注:至少一个配置文件参数被Selenium(或Geckodriver?)覆盖:首选项>隐私和安全>"阻止弹出窗口"始终被重置为关闭状态。因此,请使用关于:profiles来断言你正在运行哪个配置文件。

注意:

  • firefox_capabilities 在上述代码中可能不需要。
  • 在 Firefox 60.4.0esr (64-bit),geckodriver 0.23.0 (2018-10-04),selenium 3.141.0 with Python 3.5.3 下测试通过。

所以你这里有两个代码块,第一个应该是解决方案,但它不起作用,因为你没有在任何地方指定驱动程序位置。你知道...geckodriver吗? - Eight Rice
请忽略第二个代码块。在我的代码中,创建驱动程序的行是:driver = webdriver.Firefox(fp, options=options, executable_path="path-to-geckodriver") - Gabriel Devillers

7
在Windows上我使用:
fp = webdriver.FirefoxProfile('C:/Users/x/AppData/Roaming/Mozilla/Firefox/Profiles/some-long-string')
driver = webdriver.Firefox(firefox_profile=fp)
...

1 - 要查找当前的配置文件夹,请在URL字段中输入about:support并按回车键。
2 - 要查看所有用户配置文件,请在URL字段中输入about:profiles并按回车键。


1
这对我有效,但是请注意,使用“根目录”而不是本地目录。我一直试图使用本地目录,但从未成功。一旦我改为使用根目录,就完美地工作了。您可以通过在Firefox中输入“about:profiles”来查找您的根目录和本地目录位置。 - Dave

3
您没有更新配置文件的偏好设置: profile.update_preferences()。在设置偏好后,您必须更新该配置文件。请按照以下代码进行操作:
from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary

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/vnd.ms-excel'))
profile.set_preference('general.warnOnAboutConfig', False)
profile.update_preferences()
gecko_path = "path_to_geckodriver\\geckodriver.exe"
path = "path_to_firefoxs\\Mozilla Firefox\\firefox.exe"
binary = FirefoxBinary(path)
driver = webdriver.Firefox(firefox_profile=profile,executable_path=gecko_path)

-1

切换到Chrome驱动程序。目前Firefox、gecko和selenium在一起运作效果不佳。以下是最终对我有用的内容。

import unittest
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException

class TestTemplate(unittest.TestCase):
    """Include test cases on a given url"""

    def setUp(self):
        """Start web driver"""
        chrome_options = webdriver.ChromeOptions()
        chrome_options.add_argument('--no-sandbox')
        self.driver = webdriver.Chrome(chrome_options=chrome_options)
        self.driver.implicitly_wait(10)

    def tearDown(self):
        """Stop web driver"""
        self.driver.quit()

    def test_case_1(self):
        """Go to python.org and print title"""
        try:
            self.driver.get('https://www.python.org/')
            title = self.driver.title
            print title
        except NoSuchElementException as ex:
            self.fail(ex.msg)

    def test_case_2(self):
        """Go to redbull.com and print title"""
        try:
            self.driver.get('https://www.redbull.com')
            title = self.driver.title
            print title
        except NoSuchElementException as ex:
            self.fail(ex.msg)

if __name__ == '__main__':
    suite = unittest.TestLoader().loadTestsFromTestCase(TestTemplate)
    unittest.TextTestRunner(verbosity=2).run(suite)

我使用Jenkinsfile加载帧缓冲区来调用Selenium和Python脚本。

您可以轻松在本地机器上运行此文件。您可能需要使用Linux启动vagrant box。

以下是启动Python脚本的内容。

sh "(Xvfb :99 -screen 0 1366x768x16 &) && (python ./${PYTHON_SCRIPT_FILE})"

这是从运行此Docker镜像的docker文件中调用的。

https://github.com/cloudbees/java-build-tools-dockerfile


-1

在Java中加载自定义的Firefox配置文件:

FirefoxOptions options = new FirefoxOptions();

ProfilesIni allProfiles = new ProfilesIni();         
FirefoxProfile selenium_profile = allProfiles.getProfile("selenium_profile"); // manualy created profile in firefox profile manager
options.setProfile(selenium_profile);

options.setBinary("C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");
System.setProperty("webdriver.gecko.driver", "C:\\Users\\pburgr\\Desktop\\geckodriver-v0.20.0-win64\\geckodriver.exe");
driver = new FirefoxDriver(options);
driver.manage().window().maximize();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接