How to reuse existing Selenium browser session

Suppose you are running a long Selenium test. The test runs fine but fails towards the end as some element was not found or was not clickable. Ideally, you would like to fix the locator and check it immediately. Now you wonder if you can reuse your browser session from the same point where the failure occurred. This post shows you how to do just that! This would help you to debug the locators used quickly, instead of running your whole test again.


Extract session_id and _url from driver object

We are taking advantage of the fact that Selenium lets you attach a driver to a session id and an URL. You can extract your session id and _url from the driver object as mentioned below

session_url = driver.command_executor._url  
session_id = driver.session_id

Tie it up with your framework

In case you are using a framework, you can print out the session id and url in the method where you try to get the element. In an example shown below, I am using a get_element method which would return the DOM element. I am printing the session id and url whenever the find_element method fails

def get_element(self,xpath):
        "Return the DOM element of the xpath or 'None' if the element is not found "
        dom_element = None
        try:
            dom_element = self.driver.find_element(xpath)
        except Exception,e:
            self.write(str(e),'debug')
            self.write("Check your locator-'%s"%xpath)
            #Print the session_id and _url in case the element is not found
            self.write("In case you want to reuse session, the session_id and _url for current browser session are: %s,%s"%(driver.session_id ,driver.command_executor._url))
 
        return dom_element

Use the session id and url

Now you can use the session id and url, in order to debug the locators. Open python command line tool and use the below code

 
from selenium import webdriver
 
#Pass the session_url you extracted
driver = webdriver.Remote(command_executor=session_url,desired_capabilities={})
 
#Attach to the session id you extracted
driver.session_id = session_id
 
#Resume from that browser state
elm = driver.find_element_by_xpath("xpath")
 
elm.click() #Perform required action

Note1: Currently I am able to reuse the session extracted only from Chrome browser. For Firefox there are some Issue. Link 1 and Link 2

Note2: This code is present in our open-sourced Python-Selenium test automation framework based on the page object pattern. We strongly recommend you check it out!

If you are a startup finding it hard to hire technical QA engineers, learn more about Qxf2 Services.


Avinash Shetty

I am a software tester with over 14 years of experience in software testing. Currently, I am working at Qxf2 Services Bangalore. As a student of the context-driven approach to software testing, I feel there is a lot to learn out there which keeps me very excited. My work has helped me gain good experience in different areas of testing like CRM, Web, Mobile and Database testing. I have good knowledge of building test scripts using Automation tools like Selenium and Appium using Java and Python. Besides testing, I am a “Sports Fanatic” and love watching and playing sports.

17 Comments

  1. Joakim Bäcklund said:

    Thank you for this!
    In my case the webdriver.remote opens a new completely empty window above the existent one.

    It’s circumvented by sendKeys Alt+F4 and/or AppActivate(“Google Chrome”)
    Those functions can be found in win32com.client

    May 24, 2017
    Reply
    • Avinash Shetty Avinash Shetty said:

      I too observed the empty window opening up. Thanks for letting me know how to find a way around it.

      May 26, 2017
      Reply
    • Denis Zvezdov said:

      Actually, to fix this annoying empty window issue, you should just close browser before you re-set session_id for it:

      cls.browser = webdriver.Remote(command_executor=session_url, desired_capabilities={})
      cls.browser.close()
      cls.browser.session_id = session_id

      June 30, 2017
      Reply
  2. Thenmozhi said:

    Is this possible to acheive using java code.

    July 19, 2017
    Reply
  3. Jhony said:

    Hi, the code no longer works.
    I am using selenium 3.9.0 with python, your code ever open new browser.
    I tested with chromedriver and geckodriver(firefox).
    Please, inform version of your selenium

    February 22, 2018
    Reply
    • Avinash Shetty Avinash Shetty said:

      Hi Jhony,
      Can you let me know what error you get when you try out the code?. Yes, the code opens a new browser session and you can try the suggestions in some of the above comments to fix that issue. My selenium version is 3.6.0

      February 23, 2018
      Reply
    • Anonymous said:

      Because of the version compactability between your selenium and firefox driver it will not work. Try o downgrade your firefox driver

      July 5, 2018
      Reply
  4. heipark said:

    the best way to void create a emtpy windows is mock start_session(), the code below:

    def start_session(self, *args):
    ”’ mock method, to void create a emtpy chrome page ”’
    pass

    def reuse_driver(url, session_id):
    webdriver.Remote.start_session = start_session # user mocked method, do nothing
    driver = webdriver.Remote(command_executor=url)
    driver.session_id = session_id
    driver.w3c = None
    return driver

    June 26, 2018
    Reply
  5. Has anyone tried this when running Selenium on Browserstack?…

    When launching the new driver, it seems it’s not possible to change the session id. (driver.session_id = session_id ) So the browserstack session gets stuck.

    Any tips or advice would be really helpful…

    September 18, 2018
    Reply
    • Rohan Joshi Rohan Joshi said:

      Gilles Vanermen , we haven’t tried this with browserstack . But this was meant to help debugging tests on local system to save time

      September 19, 2018
      Reply
  6. John said:

    If the browser session was opened by some other application and we want to perform automation on that browser session, then is it possible?

    December 3, 2019
    Reply
    • Avinash Shetty Avinash Shetty said:

      Hi John,
      We need session_id and Session_url to do this. I don’t know of a way to get this for an already opened session by some other application

      December 4, 2019
      Reply
  7. Anonymous said:

    Was looking for this particular implementation of reusing the browser, but not found in your framework, where is it ?

    February 6, 2020
    Reply
    • Indira Nellutla Indira Nellutla said:

      Hi,

      The posts only gives an example on how you can use session id and url in the framework. In this example we are printing the session id and url whenever the find_element method fails. You can print out the session details in the method where you try to get the element.

      I hope this information helps !!!

      February 7, 2020
      Reply
  8. Ari said:

    Hi nice information,

    Am I right about this:( in my understanding) your code is that you run fistly run it via python so because of that, you can get the ID of
    session_url = driver.command_executor._url
    session_id = driver.session_id
    but how to use already opened selenium(manual opening or already open by other python script that already stop). Let say we have opened 3 window selenium. How to get the list the session ID of that three ‘session_url’ and ‘session_id’ and so we can control the right one which opened the url https://google.com.

    February 13, 2020
    Reply
    • Akkul D N said:

      Hi,
      You could use get.windowshandles() to store all the session ids of the open windows. You could also print store the session_id as soon as the window is spawned.
      I would suggest using a similar code:

      windows= get.windowhandles()
      for window in windows:
             driver.switch_to_window(window)
             url=driver.getCurrentUrl()
             print(url)
             if url='google.com':
                        print("window")
      
      February 14, 2020
      Reply

Leave a Reply

Your email address will not be published.