How can I start a webdriver instance in flask server and use it globally

Viewed 132

I have this function which I want it to be called in the main function in flask app, and want to pass it to another class. The catch here is I want to create the instance only once while starting the server and have to pass it globally to all the classes

def webdriver_instance():
    from selenium import webdriver
    from selenium.webdriver import FirefoxOptions
    opts = FirefoxOptions()
    opts.add_argument("--headless")
    opts.add_argument("start-maximized")
    opts.add_argument("disable-infobars")
    opts.add_argument("--disable-extensions")
    opts.add_argument('--no-sandbox')
    opts.add_argument('--disable-application-cache')
    opts.add_argument('--disable-gpu')
    opts.add_argument("--disable-dev-shm-usage")
    browser = webdriver.Firefox(firefox_options=opts)

    return browser
1 Answers

you are looking for re-using selenium sessions. You can start the browser on once and store the session id and executor url somewhere and grab it, when needed:

from selenium import webdriver

driver = webdriver.Firefox()
executor_url = driver.command_executor._url
session_id = driver.session_id
driver.get("http://tarunlalwani.com")

print session_id
print executor_url

def create_driver_session(session_id, executor_url):
    from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver

    # Save the original function, so we can revert our patch
    org_command_execute = RemoteWebDriver.execute

    def new_command_execute(self, command, params=None):
        if command == "newSession":
            # Mock the response
            return {'success': 0, 'value': None, 'sessionId': session_id}
        else:
            return org_command_execute(self, command, params)

    # Patch the function before creating the driver object
    RemoteWebDriver.execute = new_command_execute

    new_driver = webdriver.Remote(command_executor=executor_url, desired_capabilities={})
    new_driver.session_id = session_id

    # Replace the patched function with original function
    RemoteWebDriver.execute = org_command_execute

    return new_driver

driver2 = create_driver_session(session_id, executor_url)
print driver2.current_url

source: https://tarunlalwani.com/post/reusing-existing-browser-session-selenium/

Related