1

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()
Hishan_98
  • 136
  • 1
  • 11
  • 1
    Does this answer your question? [Python selenium keep browser open](https://stackoverflow.com/questions/51865300/python-selenium-keep-browser-open) – m_____z Nov 17 '19 at 13:15
  • 1
    Can't reproduce. Is that the exact code? do you have `driver.close()/driver.quit()` somewhere? – Guy Nov 17 '19 at 13:17
  • Are you waiting for the last action to complete (and then presumably asserting on a condition)? – orde Nov 17 '19 at 18:24

3 Answers3

2

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

Prithu Srinivas
  • 135
  • 1
  • 1
  • 7
1

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()
0

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()