Webdriver:未定义名称“ driver”

问题描述

我正在编写一个使用Firefox Webdriver的python脚本。但是,在满足条件之前,不应创建浏览器实例。

在测试是否已经打开浏览器时,Spyder的编辑器中会显示一条消息:未定义名称'driver'。

如何更改代码以消除该消息?

while True
    if time_to_work():
        if driver.service.is_connectable():            
            do_something()
        else:
            driver = webdriver.Firefox(profile,options=options)
            print('browser started..')
    else:
        if driver.service.is_connectable():
            print('Closing browser..')        
            driver.quit()        

解决方法

如果没有driver.service.is_connectable()实例,则无法测试driver,因此您需要在while True之前声明驱动程序实例。您可以使用{p>初始化driver实例,而不会显示实际的浏览器窗口

options = Options()
options.headless() = True

并使用

初始化驱动程序
driver = webdriver.Firefox(options=options,executable_path=r'[YOUR GECKODRIVER PATH]')

(由于找到了接受的答案here)。 然后,您可以检查time_to_work()以及其他条件。

,

要在第一遍打开浏览器(延迟加载),请将driver初始化为None,然后检查time_to_work中的值

尝试以下代码:

driver = None
while True
    if time_to_work():
        if not driver: # start browser
            driver = webdriver.Firefox(profile,options=options)
            print('Browser started..')
        do_something()
    else:
        if driver:
            print('Closing browser..')        
            driver.quit() 
            driver = None