0

I'm writing a python script that uses Firefox webdriver. However, the browser instance should not be created until a condition is met.

When testing if browser is already opened, there is a message in Spyder's editor: undefined name 'driver'.

How to change the code to get rid of that message?

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()        
Rimfire
  • 378
  • 1
  • 3
  • 12

2 Answers2

0

There's no way to test driver.service.is_connectable() if there's no driver instance, so you'll need to have the driver instance declared before the while True. You can have the driver instance initialized without the actual browser window showing up by using

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

and initializing the driver using

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

(thanks to the accepted answer found here). Then you can check time_to_work() along with the other conditions.

Dharman
  • 30,962
  • 25
  • 85
  • 135
lionrocker221
  • 171
  • 3
  • 8
  • This is what I did before, but there is very little memory on my VPS. I'm looking for a way to have an instance only when the "time_to_work" condition is true. – Rimfire Sep 20 '20 at 01:04
0

To open the browser on the first pass (lazy loading), initialize the driver to None then check the value in time_to_work

Try this code:

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
  • 11,175
  • 2
  • 7
  • 15
  • That works fine the first run. But during the second time in the loop occurs an exception: ConnectionRefusedError ErrNo(111) Full log at: https://justpaste.it/1qn1l – Rimfire Sep 20 '20 at 12:49
  • Here is the small testscript I ran to test the idea with driver = None. https://justpaste.it/2r61a – Rimfire Sep 20 '20 at 12:53
  • Answer updated to reset the driver to None. You should change your logic so you only need to open\close the browser once. – Mike67 Sep 20 '20 at 14:17