0

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?

1 Answer 1

1

@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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer. I' ve anyway found that it does the job just by letting the function return driver and all the variables you will need for the rest of the code. Anyhow don't know if it' s the best solution, but it is sufficient to return driver to keep the browser open.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.