Posted on Leave a comment

How to reconnect to the browser opened by webdriver with selenium

Due to different reasons, a programmer may find it very difficult to reconnect to the browser opened by webdriver with selenium. When this happens, programming work will become stagnant. Therefore, this article will provide a way out.

What to do

Usually, a connection URL and a session_ID is what represents the Selenium – WebDriver session. Therefore, you can reconnect with an existing one. This approach of reconnecting to the browser will utilize the Selenium internal properties, which tend to be different in new versions. As a result of this, it is advisable not to use the method explained here for production code against Remote SE.

Immediately after the webdriver instance is launched, it is crucial to access the properties that were noted earlier. A sample of this is provided below:

from selenium import webdriver

driver = webdriver.Chrome()
driver.get('https://www.google.com/')

now Google is opened, the browser is fully functional; print the two properties
command_executor._url (it's "private", not for a direct usage), and session_id
print(f'driver.command_executor._url: {driver.command_executor._url}')
print(f'driver.session_id: {driver.session_id}')

After establishing both properties, then it is easy to connect another instance, which will help launch a remote driver as well as the URL included above. Doing this will help connect the running Selenium process below:

driver2 = webdriver.Remote(command_executor=the_known_url) 
when the started selenium is a local one, the url is in the form 'http://127.0.0.1:62526'

New Browser Window

After successfully running the code, a new browser window will be launched subsequently due to the automatic launch of a new session by the Selenium library, thus resulting in two sessions in a single webdriver process.

When you try navigating a URL afterwards, it is possible to notice the execution on the new browser instance as opposed to the results obtained from the initial start, which was not desired. When you find yourself at this point, there are a couple of things that need to be done. First of which is exiting the SE session, after which you then switch to the initial (old) SE Session.

This is displayed below:

if driver2.session_id != the_known_session_id:   # this is pretty much guaranteed to be the case
driver2.close() # this closes the session's window - it is currently the only one, thus the session itself will be auto-killed, yet:
driver2.quit() # for remote connections (like ours), this deletes the session, but does not stop the SE server
take the session that's already running
driver2.session_id = the_known_session_id
do something with the now hijacked session:
driver.get('https://www.bing.com/')

Conclusion

Simple and straightforward, just like that, you are successfully reconnected to the initial SE sessions you were on, containing all the properties before disconnection i.e. cookies.