selenium.common.exceptions.WebDriverException: Message: invalid session id using Selenium with ChromeDriver and Chrome through Python

invalid session id

The invalid session ID error is a WebDriver error that occurs when the server does not recognize the unique session identifier. This happens if the session has been deleted or if the session ID is invalid.

A WebDriver session can be deleted through either of the following ways:

  • Explicit session deletion: A WebDriver session is explicitly deleted when explicitly invoking the quit() method as follows:

    • Code Block:

      from selenium import webdriver
      from selenium.common.exceptions import InvalidSessionIdException
      
      driver = webdriver.Chrome(executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
      print("Current session is {}".format(driver.session_id))
      driver.quit()
      try:
          driver.get("https://www.google.com/")
      except Exception as e:
          print(e.message)
      
    • Console Output:

      Current session is a9272550-c4e5-450f-883d-553d337eed48
      No active session with ID a9272550-c4e5-450f-883d-553d337eed48
      
  • Implicit session deletion: A WebDriver session is implicitly deleted when you close the last window or tab invoking close() method as follows:

    • Code Block:

      driver = webdriver.Chrome(executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
      print("Current session is {}".format(driver.session_id))
      # closes current window/tab
      driver.close()
      try:
          driver.get("https://www.google.com/")
      except Exception as e:
          print(e.message)
      
    • Console Output:

      Current session is a9272550-c4e5-450f-883d-553d337eed48
      No active session with ID a9272550-c4e5-450f-883d-553d337eed48
      

Conclusion

As the first one request works fine but for others you get a session ID error most possibly the WebDriver controled Web Browser is getting detected and hence blocking the next requests.

There are different reasons for the WebDriver controled Web Browser to get detected and simultaneously get blocked. You can find a couple of detailed discussion in:

Leave a Comment