为什么我在尝试创建这个无尽的 selenium 循环时会出错?

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

我正在使用以下 selenium 代码:​​

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

想法是 chrome 浏览器在无限循环中打开和关闭。当我 运行 它时,我得到 'max retry error'。我该如何解决这个问题?

第一次执行 driver.quit() 时,它会终止浏览器实例。对于第二次迭代,必须执行的第一行将是 driver.get("https://www.google.com/"),现在由于驱动程序对象已在第一次迭代中被杀死,因此驱动程序在第二次迭代中为空。结果

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

要解决这个问题,

解决方案:您应该为每次迭代创建一个驱动程序实例。

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

    i = i + 1