Lawless Leopard
Lawless Leopard

Reputation: 69

How can I keep a selenium webdriver alive?

I'm trying to write a selenium test in python, where i would need to start a selenium webdriver and keep that driver alive so it can be called in other functions (defs) to get webpages.

I'm trying to do this in order to considerably reduce execution time.

Any suggestions / insights would be highly appreciated thank you all.

UPDATE

The following is a piece of sample code to illustrate what I am trying to achieve. Ideally I would like chromedriver to stay open between the two function calls to avoid having to tear it down and restart chromedriver which takes a lot of time, if you have multiple (50+) function calls.

def chromedriver_function(url):    
    # Start Webdriver
    options = webdriver.ChromeOptions()
    options.add_argument('--headless')
    options.add_argument("--disable-gpu")
    options.add_argument("--no-sandbox")
    options.add_argument("--disable-dev-shm-usage")
    driver = webdriver.Chrome(chrome_options=options, executable_path="/opt/chromedriver")

    driver.get(url)

    return driver.page_source

def function1()
    ... do something
    chromedriver_function("http://www.example.com")

def function2()
    ... do something
    chromedriver_function("http://www.mysecondpage.com") 

Upvotes: 0

Views: 4668

Answers (1)

Jordan
Jordan

Reputation: 515

Just create the driver and return its value. Then call your function using this value as parameter

def create_driver():
        options = webdriver.ChromeOptions()
        options.add_argument('--headless')
        options.add_argument("--disable-gpu")
        options.add_argument("--no-sandbox")
        options.add_argument("--disable-dev-shm-usage")
        driver = webdriver.Chrome(chrome_options=options, executable_path="/opt/chromedriver")
        return driver

def chromedriver_function(driver,url):    
    # Do whatever you want here

    driver.get(url)

    return driver.page_source

def function1(driver)
    ... do something
    chromedriver_function("http://www.example.com")

def function2(driver)
    ... do something
    chromedriver_function("http://www.mysecondpage.com") 

And call your functions like this

driver = create_driver()
function1(driver)
function2(driver)

Upvotes: 2

Related Questions