0

In attempting to reattach selenium to a chromium session I am experiencing a keyerror:

KeyError: 'sessionId'

To reattach the session without initialising a new window, a monkey patch is used from another stackoverflow question - pasted below from @TarunLalwani

from selenium import webdriver

driver = webdriver.Firefox()
executor_url = driver.command_executor._url
session_id = driver.session_id
driver.get("http://tarunlalwani.com")

print session_id
print executor_url

def create_driver_session(session_id, executor_url):
    from selenium.webdriver.remote.webdriver import WebDriver as 
RemoteWebDriver

    # Save the original function, so we can revert our patch
    org_command_execute = RemoteWebDriver.execute

    def new_command_execute(self, command, params=None):
        if command == "newSession":
            # Mock the response
            return {'success': 0, 'value': None, 'sessionId': session_id}
        else:
            return org_command_execute(self, command, params)

    # Patch the function before creating the driver object
    RemoteWebDriver.execute = new_command_execute

    new_driver = webdriver.Remote(command_executor=executor_url, 
    desired_capabilities={})
    new_driver.session_id = session_id

    # Replace the patched function with original function
    RemoteWebDriver.execute = org_command_execute

    return new_driver

driver2 = create_driver_session(session_id, executor_url)

This monkey patch is changing the key where the error occurs, so i believe the issue is there, but i don't quite understand what is happening with the monkey patch.

Chromium will run if the monkey patch has not been loaded as a function but will not if it has, giving the above error.

Further, running the below after loading in the monkey patch

    browser = webdriver.Chrome(executable_path=path_to_chrome)
    browser.get(url)

will lead to the error, which seems to be accessing the monkey patch even when i am only calling the webdriver, not attempting to reuse a session.

<ipython-input-4-9615267dd764> in new_command_execute(self, command, params)
     14             return {'success': 0, 'value': None, 'sessionId': 
session_id}
     15         else:
---> 16             return org_command_execute(self, command, params)

How can i attempt to resolve this?

Alex
  • 1

1 Answers1

0

Rather than fixing the above, i am simply going to declare the browser outside of the function and pass it into the function i am using. Eg:

browser = webdriver.Chrome(executable_path=path_to_chrome)
browser.get(url)

somefunction(browser)

rather than

somefunction(session_id, session_url)

Less elegant in some ways but simpler.

Alex
  • 1