'After executing selenium python code google chrome closes automatically

This code runs without any error but it automatically closes the google chrome after searching w3school

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()

def google():
    driver.get("https://www.google.com")
    driver.find_element_by_xpath('//*[@id="tsf"]/div[2]/div[1]/div[1]/div/div[2]/input').send_keys('w3school')
    driver.find_element_by_xpath('//*[@id="tsf"]/div[2]/div[1]/div[3]/center/input[1]').send_keys(Keys.ENTER)

google()


Solution 1:[1]

Try the experimental options provided in the webdriver like so:

from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)

driver = webdriver.Chrome(options=options, executable_path="path/to/executable")

Caveat: This does leave chrome tabs open and detached, which you will have to manually close afterwards

Solution 2:[2]

Selenium always automatically quits after a code is finished running. You can add a time.sleep() to keep it open.

    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    import time
    driver = webdriver.Chrome()

    def google():
        driver.get("https://www.google.com")
        driver.find_element_by_xpath('//*[@id="tsf"]/div[2]/div[1]/div[1]/div/div[2]/input').send_keys('w3school')
        driver.find_element_by_xpath('//* [@id="tsf"]/div[2]/div[1]/div[3]/center/input[1]').send_keys(Keys.ENTER)
        time.sleep(10) #specify the seconds

    google()

Solution 3:[3]

you must open a browser instance outside the function so it will remain open after executing the codes inside the function

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()
driver.get("https://www.google.com")    

def google():
    driver.find_element_by_xpath('//*[@id="tsf"]/div[2]/div[1]/div[1]/div/div[2]/input').send_keys('w3school')
    driver.find_element_by_xpath('//*[@id="tsf"]/div[2]/div[1]/div[3]/center/input[1]').send_keys(Keys.ENTER)

google()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Prithu Srinivas
Solution 2 Vikrant Kaushalram
Solution 3 user18523129