Why do I get an error when trying to create this endless selenium loop?

Viewed 100

I am working with the following selenium code:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time

options=Options()

driver=webdriver.Chrome(options=options)

i = 0
while True:
    driver.get("https://www.google.com/")
    time.sleep(2)
    driver.quit()

    i = i + 1

The idea is that the chrome browser opens and closes in an endless loop. When I run it I get a 'max retry error'. How can I solve this issue?.

1 Answers

For the very first time driver.quit() gets executed, it will kill the browser instance. And for the 2nd iteration, the first line that has to be executed will be driver.get("https://www.google.com/"), now since driver object has been killed in the first iteration so the driver is null for the second iteration. Resulting in

sock.connect(sa)
ConnectionRefusedError: [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.NewConnectionError: <urllib3.connection.HTTPConnection object at 0x000001D12A2671C0>: 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:

raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='127.0.0.1', port=57911): Max retries exceeded with url: /session/eedcbdf06a0db68d2b4b6e9bc76b5167/url (Caused by NewConne

to solve this,

Solution: you should create a driver instance for each iteration.

i = 0
while True:
    driver = webdriver.Chrome(options=options)
    driver.get("https://www.google.com/")
    time.sleep(2)
    driver.quit()

    i = i + 1
Related