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

Question:

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")
Asked By: Richard

||

Answers:

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/

Answered By: Tarun Lalwani

This doesn’t work any more, it throws WinError of the target machine actively refused connection, when trying to spawn a 2nd url.

Answered By: user21381179
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.