Python Webdriver:未定义的名称';驱动程序&x27;
我正在编写一个使用FirefoxWebDriver的python脚本。但是,在满足条件之前,不应创建浏览器实例 测试浏览器是否已打开时,Spyder的编辑器中会显示一条消息:未定义的名称“driver” 如何更改代码以删除该消息Python Webdriver:未定义的名称';驱动程序&x27;,python,python-3.x,python-2.7,selenium-firefoxdriver,Python,Python 3.x,Python 2.7,Selenium Firefoxdriver,我正在编写一个使用FirefoxWebDriver的python脚本。但是,在满足条件之前,不应创建浏览器实例 测试浏览器是否已打开时,Spyder的编辑器中会显示一条消息:未定义的名称“driver” 如何更改代码以删除该消息 while True if time_to_work(): if driver.service.is_connectable(): do_something() else:
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()
如果没有
驱动程序
实例,则无法测试驱动程序.service.is_connectable()
,因此您需要在之前声明驱动程序实例,而为True
。通过使用,您可以在不显示实际浏览器窗口的情况下初始化驱动程序
实例
options = Options()
options.headless() = True
并使用
driver = webdriver.Firefox(options=options, executable_path=r'[YOUR GECKODRIVER PATH]')
(多亏找到了公认的答案)。
然后您可以检查
工作时间()
以及其他条件。要在第一次通过时打开浏览器(延迟加载),请将驱动程序初始化为无
,然后检查工作时间中的值
请尝试以下代码:
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
你用测试的是什么条件是可连接的?@Mike67我想知道是否需要创建浏览器实例。或者它已经在那里,准备获取网页。这是我以前做的,但是我的VPS上的内存很少。我正在寻找一种方法,只有当“time-to-work”条件为真时才有一个实例。这在第一次运行时效果很好。但是在循环中的第二次出现异常:connectionRefuedError ErrNo(111)Full log at:下面是我运行的小测试脚本,用于测试driver=None的idea。已更新答案以将驱动程序重置为无。您应该更改逻辑,以便只需打开/关闭浏览器一次。