Latin Bass
Latin Bass

Reputation: 291

Google chrome closes immediately after being launched with selenium

I am on Mac OS X using selenium with python 3.6.3.

This code runs fine, opens google chrome and chrome stays open.:

chrome_options = Options()
chrome_options.binary_location="../Google Chrome"
chrome_options.add_argument("disable-infobars");
driver = webdriver.Chrome(chrome_options=chrome_options)

driver.get("http://www.google.com/")

But with the code wrapped inside a function, the browser terminates immediately after opening the page:

def launchBrowser():
   chrome_options = Options()
   chrome_options.binary_location="../Google Chrome"
   chrome_options.add_argument("disable-infobars");
   driver = webdriver.Chrome(chrome_options=chrome_options)

   driver.get("http://www.google.com/")
launchBrowser()

I want to use the same code inside a function while keeping the browser open.

Upvotes: 29

Views: 118032

Answers (18)

Petar Petrov
Petar Petrov

Reputation: 752

My guess is that the driver gets garbage collected, in C++ the objects inside a function (or class) get destroyed when out of context. Python doesn´t work quite the same way but its a garbage collected language. Objects will be collected once they are no longer referenced.

To solve your problem you could pass the object reference as an argument, or return it.

def launchBrowser():
   chrome_options = Options()
   chrome_options.binary_location="../Google Chrome"
   chrome_options.add_argument("start-maximized");
   driver = webdriver.Chrome(chrome_options=chrome_options)

   driver.get("http://www.google.com/")
   return driver
driver = launchBrowser()

Upvotes: 30

MAVERICK
MAVERICK

Reputation: 1

#ONE OF THE BEST METHOD TO SEE RESULT

import time
from selenium import webdriver

driver=webdriver.Chrome()
driver.get("https://en.wikipedia.org/wiki/Main_Page")
data=driver.find_element(By.NAME,"search")
data.send_keys("hasan")
time.sleep(5)

Upvotes: 0

PriteshSurale
PriteshSurale

Reputation: 23

make the driver object Global, or declare driver outside funtion it will keep tab on without closing it.

Upvotes: 0

Musawer Khan Fatih
Musawer Khan Fatih

Reputation: 1

Simply copy and paste this to overcome all kind of errors and warnings:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service

chrome_driver_path = "path\to\your\chromedriver.exe"

options = Options()
options.add_argument("--remote-debugging-port=9222")  # Use an arbitrary port number
options.add_experimental_option("detach", True)  # Keep the browser window open after exiting the script

service = Service(executable_path=chrome_driver_path)
driver = webdriver.Chrome(service=service, options=options)

driver.get("https://facebook.com")

This Python code uses the Selenium library to automate the control of a web browser. Specifically, it uses the Chrome browser and the Chromedriver executable to launch the browser. It then sets some options to enable remote debugging and detach the browser window from the script. Finally, it navigates to the Facebook website using the get() method of the webdriver object. This code snippet can be used as a starting point for developing a web scraping or automated testing script using Selenium and Chrome.

Upvotes: -1

notClickBait
notClickBait

Reputation: 101

All other suggestions above do not work for me. However, all I needed to do was run pip uninstall selenium and then run pip install selenium. The reason I need to reinstall Selenium is that I install Selenium before I install Chrome, which causes the Selenium Driver not able to find the Chrome browser. Therefore, reinstalling Selenium ensures that it is able to find the Chrome browser and register it as a Chrome driver automatically. For an in-depth explanation, please see https://eokulik.com/now-you-dont-need-to-install-chromedriver/

In the code, I make sure to specify the "detach" options. Without the "detach" options, Chrome will close automatically after launch!

from selenium.webdriver.chrome.options import Options

r_options = Options()
r_options.add_experimental_option('detach', True)
driver = webdriver.Chrome(options=r_options)

Upvotes: 0

Pradip Thapa
Pradip Thapa

Reputation: 1

You can simply add:-

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

Upvotes: 0

Ashik
Ashik

Reputation: 1259

Adding experimental options detach true works here:

from selenium import webdriver

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

Upvotes: 8

20MikeMike
20MikeMike

Reputation: 23

The reason why the browser closes is because the program ends and the driver variable is garbage collected after the last line of code. For the second code in the post, it doesn't matter whether you use it in a function or in global scope. After the last statement is interpreted, the driver variable is garbage collected and the browser terminates from program termination.

Solutions: Set chrome options

Use the time module

Use an infinite loop at the end of your program to delay program closure

Upvotes: 0

harrisrk
harrisrk

Reputation: 1

Hi the below solutions worked for me Please have a try these.

Solution 1 : of Google chrome closes automatically after launching using Selenium Web Driver.

Check the Version of the Chrome Browser driver exe file and google chrome version you are having, if the driver is not compatible then selenium-web driver browser terminates just after selenium-web driver opening, try by matching the driver version according to your chrome version

Upvotes: 0

Babatunde Adeyemi
Babatunde Adeyemi

Reputation: 14448

To prevent this from happening, ensure your driver variable is defined outside your function or as a global variable, to prevent it from being garbage collected immediately after the function completes execution.

In the example above, this could mean something like:

driver = webdriver.Chrome(chrome_options=get_options())

def get_options():
   chrome_options = Options()
   chrome_options.binary_location="../Google Chrome"
   chrome_options.add_argument("disable-infobars")
   return chrome_options

def launchBrowser():
   driver.get("http://www.google.com/")

launchBrowser()

Upvotes: 0

TheLegend27
TheLegend27

Reputation: 53

To whom has the same issue, just set the driver to global, simple as following:

global driver
driver.get("http://www.google.com/")

This resolved the problem on my side, hope this could be helpful

Upvotes: 3

Anoroah
Anoroah

Reputation: 2119

To make the borwser stay open I am doing this:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

def browser_function():
    driver_path = "path/to/chromedriver"
    chr_options = Options()
    chr_options.add_experimental_option("detach", True)
    chr_driver = webdriver.Chrome(driver_path, options=chr_options)
    chr_driver.get("https://target_website.com")

Upvotes: 16

Behdad
Behdad

Reputation: 1629

Just simply add:

while(True):
    pass

To the end of your function. It will be like this:

def launchBrowser():
   chrome_options = Options()
   chrome_options.binary_location="../Google Chrome"
   chrome_options.add_argument("disable-infobars");
   driver = webdriver.Chrome(chrome_options=chrome_options)

   driver.get("http://www.google.com/")
   while(True):
       pass
launchBrowser()

Upvotes: 36

Keith Leung
Keith Leung

Reputation: 31

My solution is to define the driver in the init function first, then it won't close up the browser even the actional

Upvotes: 3

KNAPPYFLASH
KNAPPYFLASH

Reputation: 141

The browser is automatically disposed once the variable of the driver is out of scope. So, to avoid quitting the browser, you need to set the instance of the driver on a global variable:

Dim driver As New ChromeDriver

Private Sub Use_Chrome()

driver.Get "https://www.google.com"
'  driver.Quit
End Sub

Upvotes: 5

def createSession():
    **global driver**
    driver = webdriver.Chrome(chrome_driver_path)
    driver.maximize_window()
    driver.get("https://google.com")
    return driver

Upvotes: 0

Tyler Zoltowski
Tyler Zoltowski

Reputation: 41

This is somewhat old, but the answers on here didn't solve the issue. A little googling got me here

http://chromedriver.chromium.org/getting-started

The test code here uses sleep to keep the browser open. I'm not sure if there are better options, so I will update this as I learn.

import time
from selenium import webdriver

    driver = webdriver.Chrome('/path/to/chromedriver')  # Optional argument, if not specified will search path.
    driver.get('http://www.google.com/xhtml');
    time.sleep(5) # Let the user actually see something!
    search_box = driver.find_element_by_name('q')
    search_box.send_keys('ChromeDriver')
    search_box.submit()
    time.sleep(5) # Let the user actually see something!
    driver.quit() 

Upvotes: 4

undetected Selenium
undetected Selenium

Reputation: 193308

As per the code block you shared there can be 3 possible solutions as follows :

  • In the binary_location you have to change the .. to . (. denotes Project Workspace)
  • In the binary_location you have to change the .. to /myspace/chrome (Absolute Chrome Binary)
  • While initiating the driver, add the switch executable_path :

    driver = webdriver.Chrome(chrome_options=options, executable_path=r'/your_path/chromedriver')
    

Upvotes: 0

Related Questions