Python Selenium:在原始功能之外退出浏览器实例

Python Selenium: Quitting a browser instance outside of original function

我几天前开始学习 python + selenium,并且在我的 bbdc_check 功能之外 之外努力退出浏览器。 我的目标是每当我中断bbdc_check或遇到错误时,我想退出现有的浏览器从头开始。

我在退出浏览器时总是遇到错误。 driver.quit() 的错误消息是“TypeError: quit() missing 1 required positional argument: 'self'”。

我一直怀疑我应该在这里使用 class,我尝试松散地关闭 this solution,但仍然不能让它工作。任何想法表示赞赏,谢谢。

仅供参考,date_adate_b 未在此处定义,因为我删除了一堆与此问题无关的代码。假设该行代码有效。

import selenium
from selenium import webdriver
import time
import sys

breakloop = 0

def bbdc_check():
    global breakloop
    driver = webdriver.Chrome(r'C:\<some dir>\chromedriver.exe')
    driver.get('<a website>')

    # A bunch of code here to compare 2 different dates
    if (date_a < date_b):
        breakloop = 1
    else:
        driver.quit()
        time.sleep(600)
        
# The main while-loop to run the programme
while breakloop == 0:
    try:
        bbdc_check()

    # If I manually interrupt, kill the programme
    except KeyboardInterrupt:
        driver = webdriver.Chrome
        driver.quit()
        sys.exit()

    # If programme encounters error, try again from scratch
    except:
        driver = webdriver.Chrome
        driver.quit()
        time.sleep(30)

似乎您正在每个块中创建新的驱动程序对象以及您的函数 bbdc_check()。创建单个驱动程序实例并使用它。