Cannot attach to an existing Selenium session via geckodriver

徘徊边缘 提交于 2020-01-14 09:21:49

问题


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)?


回答1:


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 .




回答2:


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


来源:https://stackoverflow.com/questions/37963785/cannot-attach-to-an-existing-selenium-session-via-geckodriver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!