Can Selenium interact with an existing browser session? Can Selenium interact with an existing browser session? selenium selenium

Can Selenium interact with an existing browser session?


This is a duplicate answer **Reconnect to a driver in python selenium ** This is applicable on all drivers and for java api.

  1. open a driver
driver = webdriver.Firefox()  #python
  1. extract to session_id and _url from driver object.
url = driver.command_executor._url       #"http://127.0.0.1:60622/hub"session_id = driver.session_id            #'4e167f26-dc1d-4f51-a207-f761eaf73c31'
  1. Use these two parameter to connect to your driver.
driver = webdriver.Remote(command_executor=url,desired_capabilities={})driver.close()   # this prevents the dummy browserdriver.session_id = session_id

And you are connected to your driver again.

driver.get("http://www.mrsmart.in")


This snippet successfully allows to reuse existing browser instance yet avoiding raising the duplicate browser. Found at Tarun Lalwani's blog.

from selenium import webdriverfrom selenium.webdriver.remote.webdriver import WebDriver# executor_url = driver.command_executor._url# session_id = driver.session_iddef attach_to_session(executor_url, session_id):    original_execute = WebDriver.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 original_execute(self, command, params)    # Patch the function before creating the driver object    WebDriver.execute = new_command_execute    driver = webdriver.Remote(command_executor=executor_url, desired_capabilities={})    driver.session_id = session_id    # Replace the patched function with original function    WebDriver.execute = original_execute    return driverbro = attach_to_session('http://127.0.0.1:64092', '8de24f3bfbec01ba0d82a7946df1d1c3')bro.get('http://ya.ru/')