如何解决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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。