4

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
  • 194
  • 1
  • 2
  • 12
  • 3
    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

5 Answers5

11

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
  • 245
  • 1
  • 3
  • 9
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()
1

Because "driver" variable is local variable in your function, so when the function have done, the "driver" variable will be remove and then the browser close automatically.

=> Solution is you set "driver" is global variable in your program.

0

I use the chromedriver to open chrome.

  1. download the chrome driver based on your chrome version.
  2. unzip the chrome driver to the below path in your C drive.
  3. Then use the below code to open the chrome webpage.
chromepath = 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe'
driver = webdriver.Chrome(executable_path=chromepath)
Hope
  • 11
  • 3
0

in my case the version of chrome driver needed to be replaced by currenct version of my chrome.

abnouf
  • 1