Python selenium keep browser open

If you want chrome and chromedriver to stay open, you have to use the 'detach' option when starting chromedriver.

In your case add :

from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_experimental_option("detach", True)

Or you can run the code in debug mode with breakpoint at the end and when it pauses 'kill' the program and take over the browser if you want to, but this works in IDE only.

EDIT - added the import for clarity


You can also add global browser like so:

def open_instagram():    
    try:
        # Connect
        chrome_options = webdriver.ChromeOptions()
        chrome_options.add_argument("--incognito")
        global browser # this will prevent the browser variable from being garbage collected
        browser = webdriver.Chrome('drivers/chromedriver.exe', chrome_options=chrome_options)
        browser.set_window_size(1800, 900)
        browser.get("https://www.instagram.com/accounts/login/?hl=de")
        browser.find_element(By.NAME, 'username').send_keys('MYEMAIL', Keys.TAB, 'MYPW', Keys.ENTER)
    except Exception as e:
        print (e, 'Instagram')

open_instagram()

Source