22

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.

Latin Bass
  • 221
  • 1
  • 2
  • 4
  • Not sure if that's the reason of your problems. But your code differs between these two examples. `"disable-infobars"` vs. `"start-maximized"` – Grzegorz Oledzki Nov 27 '17 at 10:39

17 Answers17

29

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()
Behdad
  • 1,459
  • 3
  • 24
  • 36
26

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()
Petar Petrov
  • 702
  • 5
  • 14
  • 1
    This answer should be checked! +1 up vote for explaining the **garbage** concept. Clearly it's the main cause of it – Ice Bear Oct 18 '21 at 06:58
  • Hi. Will this concept still work if I close the python program? In my case, I am opening a webpage using a python script. Once the page is loaded and there are no errors, I want the python program to end. But I do not want to close the browser. I want to continue working on the browser manually. Can we do that? – Meet Jan 21 '22 at 11:29
  • @Meet I expect weird things to happen that way. You could instead spawn your browser with the debug port open, and connect your webdriver to it. – Petar Petrov Mar 02 '22 at 12:41
12

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")
Anoroah
  • 1,987
  • 2
  • 20
  • 31
5

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
KNAPPYFLASH
  • 141
  • 1
  • 5
3

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

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

3

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

3

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)
Ashik
  • 1,204
  • 12
  • 22
0

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')
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
0
def createSession():
    **global driver**
    driver = webdriver.Chrome(chrome_driver_path)
    driver.maximize_window()
    driver.get("https://google.com")
    return driver
Laurenz Albe
  • 209,280
  • 17
  • 206
  • 263
0

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()
Babatunde Adeyemi
  • 14,360
  • 4
  • 34
  • 26
0

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

0

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

20MikeMike
  • 13
  • 4
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 25 '22 at 18:16
0

You can simply add:-

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

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)
notClickBait
  • 101
  • 1
  • 1
  • 12
0

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

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 25 '23 at 06:09
-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.

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 08 '23 at 11:16