Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 531
Latin Bass Avatar asked Nov 27 '17 10:11

Latin Bass


3 Answers

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()
like image 139
Petar Petrov Avatar answered Oct 09 '22 04:10

Petar Petrov


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()
like image 12
Behdad Avatar answered Oct 09 '22 05:10

Behdad


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
like image 5
KNAPPYFLASH Avatar answered Oct 09 '22 04:10

KNAPPYFLASH