Search code examples
pythonselenium-webdriverfirefoxautomation

How do I get Selenium on python to connect to an existing instance of Firefox - I am unable to connect to the marionette port


I am trying to use Selenium to connect to existing instance of Firefox - the documentation says to use something like this

options=webdriver.FirefoxOptions()
options.binary_location = r'C:\Program Files\Mozilla Firefox\firefox.exe'


webdriver_service = Service(r'c:\tmp\geckodriver.exe')
driver = webdriver.Firefox(service = webdriver_service, service_args=['--marionette-port', '2828', '--connect-existing'])

However, I get the error

    driver = webdriver.Firefox(service = webdriver_service, service_args=['--marionette-port', '2828', '--connect-existing'])
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: WebDriver.__init__() got an unexpected keyword argument 'service_args'

I see other questions about "unexpected keyword argument", they say latest versions of Selenium has other ways of passing arguments through Options.

I tried

options.add_argument('--marionette-port')
options.add_argument('2828') 
options.add_argument('--connect-existing')

But it still seems to create a new instance of Firefox

I have started firefox with the following arguments

"C:\Program Files\Mozilla Firefox\firefox.exe" -marionette -start-debugger-server 2828

How do I fix this?


These are my versions

Python version

python --version
Python 3.12.2

Selenium version

pip show selenium
Name: selenium
Version: 4.18.1

Geckodriver version

geckodriver --version
geckodriver 0.34.0 (c44f0d09630a 2024-01-02 15:36 +0000)

Firefox 123.0 (64-bit)

Windows 11


Solution

  • You should put the service_args parameter in the Service class and not on Firefox. I believe this should work

    options=webdriver.FirefoxOptions()
    options.binary_location = r'C:\Program Files\Mozilla Firefox\firefox.exe'
    
    
    webdriver_service = Service(r'c:\tmp\geckodriver.exe', service_args=['--marionette-port', '2828', '--connect-existing'])
    driver = webdriver.Firefox(service = webdriver_service)