Richard
Richard

Reputation: 135

I can reattach to session with selenium but cannot stop it launching another browser?

this is my code, it DOES attach to the old session, however on calling webdriver.Remote() it makes another browser launch!! for no reason? This is on Mac, does anyone else have this issue? (it makes this feature useless)

can anyone tell me what i am doing wrong?

from selenium import webdriver

driver = webdriver.Chrome()
url = driver.command_executor._url
session_id = driver.session_id 

driver.get('https://www.w3schools.com/html/tryit.asp?filename=tryhtml_intro')

driver2 = webdriver.Remote(command_executor=url,desired_capabilities={})
driver2.session_id = session_id

driver2.get("http://www.wikipedia.in")

Upvotes: 2

Views: 3245

Answers (1)

Tarun Lalwani
Tarun Lalwani

Reputation: 146630

You can do that but it needs some patching to selenium code. This can be done using monkey patching in python. Below is the code for the same

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)
print driver2.current_url

The key of the solution is not to let newSession command get executed through the original driver, rather handle it send our own existing session id. Which we do in the below part

    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)

PS: Detailed article available on http://tarunlalwani.com/post/reusing-existing-browser-session-selenium/

Upvotes: 3

Related Questions