Selenium error with driver.quit() and driver.close()

I have the following code:

from selenium import webdriver
driver = webdriver.Chrome("chromedriver.exe")

def login():
    driver.get(...)

while True:
    input()
    login()
    driver.quit()
    driver.close()

Let me explain:
I want when I type something, the browser opens, login() executes, and the browser closes. But when I enter something a second time, I get errors:

ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it

urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0x000002083D14DC60>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it

During handling of the above exception, another exception occurred:

urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='localhost', port=61012): Max retries exceeded with url: /session/17e2df6fcf1ef1c5281fe3b84195b8dd/url (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x000002083D14DC60>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it'))

>Solution :

There are a couple issues:

  1. You are trying to close the browser after quitting the driver instance. .close() closes the browser tab, .quit() completely quits the browser instance. You don’t need both, .quit() will take care of both.

  2. You are quitting the driver instance INSIDE your loop but never creating a new browser instance. You either need to pull the .quit() outside the loop or create a new browser instance inside the loop. It sounds like you want to do the latter.

The updated code would look like

from selenium import webdriver
driver = None

def login():
    driver = webdriver.Chrome("chromedriver.exe")
    driver.get(...)

while True:
    input()
    login()
    driver.quit()

Leave a Reply