Alex Morozov
Alex Morozov

Reputation: 5993

Cannot attach to an existing Selenium session via geckodriver

After upgrading to geckodriver I'm unable to reuse my Selenium's sessions. Here's my setup:

I have a start_browser.py script, which launches a Firefox instance and prints a port to connect to, like:

firefox_capabilities = DesiredCapabilities.FIREFOX
firefox_capabilities['marionette'] = True
browser = webdriver.Firefox(capabilities=firefox_capabilities)
print browser.service.port
wait_forever()

... and another script, which tries to connect to the existing instance via Remote driver:

caps = DesiredCapabilities.FIREFOX
caps['marionette'] = True
driver = webdriver.Remote(
        command_executor='http://localhost:{port}'.format(port=port),
        desired_capabilities=caps)

But it seems to be trying to launch a new session, and failing with a message:

selenium.common.exceptions.WebDriverException: Message: Session is already started

Is there an ability to just attach to the existing session, like in previous versions of Selenium? Or is this an intended behaviour of geckodriver (hope not)?

Upvotes: 6

Views: 6925

Answers (2)

Alex Morozov
Alex Morozov

Reputation: 5993

Alright, so unless anyone comes up with more elegant solution, here's a quick dirty hack:

class SessionRemote(webdriver.Remote):
    def start_session(self, desired_capabilities, browser_profile=None):
        # Skip the NEW_SESSION command issued by the original driver
        # and set only some required attributes
        self.w3c = True

driver = SessionRemote(command_executor=url, desired_capabilities=caps)
driver.session_id = session_id

The bad thing is that it still doesn't work, complaining that it doesn't know the moveto command, but at least it connects to a launched browser.

Update: Well, geckodriver seems to lack some functionality at the moment, so if you guys are going to keep using Firefox, just downgrade it to a version which supports old webdriver (45 plays fine), and keep an eye on tickets like https://github.com/SeleniumHQ/selenium/issues/2285 .

Upvotes: 4

RemcoW
RemcoW

Reputation: 4336

You can reconnect to a session by using the session id.

firefox_capabilities = DesiredCapabilities.FIREFOX
firefox_capabilities['marionette'] = True
browser = webdriver.Firefox(capabilities=firefox_capabilities)
print browser.service.port
wait_forever()

# get the ID and URL from the browser
url = browser.command_executor._url
session_id = browser.session_id

# Connect to the existing instance
driver = webdriver.Remote(command_executor=url,desired_capabilities={})
driver.session_id = session_id

Upvotes: 0

Related Questions