简体   繁体   中英

Python "with" statement for Selenium driver

A part of my script is scraping results from Selenium WebDriver and because my code is supposed to run forever (until I close it) I don't really have a way of implementing driver.quit() method. I tried doing this with a "with" statement but the driver just closes after init_driver() has been executed:

from selenium import webdriver

def init_driver():
    driver = webdriver.Firefox(executable_path='geckodriver.exe')
    driver.get('https://www.lsbet.com/live')

    return driver

while True:
    with init_driver() as driver:
        ... # Do something

Maybe this

with init_driver() as driver:
    while True:
        #...Do stuff
        if condition == False:
            driver.quit()
            break

I guess you can notably use contextlib from the standard library to actually implement your init_driver function as a context manager.

For example, using the simplest way with @contextlib.contextmanager decorator, it could be something like:

from contextlib import contextmanager

@contextmanager
def init_driver(options, profile):
    try:
        driver = webdriver.Firefox(executable_path='geckodriver.exe')
        driver.get('https://www.lsbet.com/live')
        yield driver
    finally:
        # code to close/quit your driver
        pass

(note the use of yield instead of return )

You can use a context manager.

class SeleniumManager:
    def __init__(self):
        pass

    def __enter__(self):
        # Setup logic goes here...
        print('I have started...')

    def __exit__(self, exc_type, exc_val, exc_tb):
        # Teardown logic goes here...
        print('I am finished...')

with SeleniumManager() as sm:
    # Your logic here...
    print('I am working on something...')

After your logic under the with statement is finished, the context manager will automatically call the exit () method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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