繁体   English   中英

Webdriver:未定义名称“驱动程序”

[英]Webdriver: Undefined name 'driver'

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

在测试浏览器是否已经打开时,Spyder 的编辑器中有一条消息:未定义名称“驱动程序”。

如何更改代码以摆脱该消息?

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实例,则无法测试driver.service.is_connectable() ,因此您需要在while True之前声明驱动程序实例。 您可以使用以下命令在不显示实际浏览器窗口的情况下初始化driver实例

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

并使用初始化驱动程序

driver = webdriver.Firefox(options=options, executable_path=r'[YOUR GECKODRIVER PATH]')

(感谢在此处找到的已接受答案)。 然后您可以检查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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM