Hishan_98
Hishan_98

Reputation: 210

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

Upvotes: 5

Views: 23307

Answers (6)

Lucas Eduardo
Lucas Eduardo

Reputation: 1

Using Edge, i didn't find the option "executable_path" to follow the steps Prithu Srinivas gave, but using the code below, the window stoped closing automatically:

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

browser = webdriver.Edge(options=options, keep_alive=True)

The same goes if i don't use the argument "keep_alive=True".

Upvotes: 0

abnouf
abnouf

Reputation: 1

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

Upvotes: 0

Hope
Hope

Reputation: 9

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)

Upvotes: 0

nhiên Lưu
nhiên Lưu

Reputation: 11

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.

Upvotes: 1

user18523129
user18523129

Reputation: 31

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

Upvotes: 3

Prithu Srinivas
Prithu Srinivas

Reputation: 275

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

Upvotes: 12

Related Questions