Luca Giovanni Voglino
Luca Giovanni Voglino

Reputation: 105

Keep browser open after executing function in Selenium Python

I want to create a function that opens the browser, just to have it in a more compact way every time I need to call it, using Selenium Python. This the code:

def prepare_website():

   chrome_driver = ChromeDriverManager().install()
   driver = Chrome(service=Service(chrome_driver))
   driver.maximize_window()

   driver.get(some_link)

prepare_website()

The problem is that after executing it closes the browser. How to keep it open instead, as it actually would do if it were not in a function?

Upvotes: 0

Views: 1866

Answers (1)

ketanvj
ketanvj

Reputation: 511

@Luca Giovanni Voglino, you can try the following modified code. basically detach option will close the driver but keep the browser open:

def prepare_website():
   chrome_options = Options()
   chrome_options.add_experimental_option("detach", True)
   chrome_driver = ChromeDriverManager().install()
   driver = Chrome(options=chrome_options, service=Service(chrome_driver))
   driver.maximize_window()

   driver.get("http://www.google.com")

prepare_website()

you will need to add the following import:

from selenium.webdriver.chrome.options import Options

Upvotes: 1

Related Questions