2

I am running a basic python program to open the Chrome Window but as soon as the code executes, the window is there for a sec and then it closes immediately.

from selenium import webdriver
import time

browser = webdriver.Chrome(executable_path=r"C:\APIR\chromedriver.exe")
browser.maximize_window()
browser.get("https://www.google.com")

Chromedriver version: 91.0.4472.101 Chrome Version: 91.0.4472.164

Any help would be appreciated.

Thank you

Phantom5X
  • 31
  • 1
  • 3
  • 1
    If this is your entire program than this is expected, add a breakpoint after the navigation to stop the script. If you have an error, post it with the full stacktrace. – Guy Jul 27 '21 at 10:32
  • 1
    @Guy : that is not expected, there is no way driver is going to kill chrome instance with the above code. – cruisepandey Jul 27 '21 at 10:40
  • @cruisepandey It does in Python, this is how the language work. – Guy Jul 27 '21 at 10:44
  • @Guy :No it does not, I checked it right after your comment, and the window still stand solid. – cruisepandey Jul 27 '21 at 10:45

2 Answers2

4

It closes because the program ends. You can:

Wait with time.sleep, for example time.sleep(10) to keep the browser open for 10 seconds after everything is done

Have the user press enter with input()

Or detect when the browser is closed. Many ways to do that. Example: https://stackoverflow.com/a/52000037/8997916

You could also catch the BrowserUnreachable exception in a loop with a small delay

DownloadPizza
  • 3,307
  • 1
  • 12
  • 27
  • Thank you for your help. I did try using the sleep method earlier but I had seen that in a couple of videos browser used to stay open hence I thought there was something wrong with the program. Detecting when the browser is closed seems like a good option. – Phantom5X Jul 27 '21 at 16:12
1

For Edge Browser

from selenium import webdriver
from selenium.webdriver.edge.service import Service
from webdriver_manager.microsoft import EdgeChromiumDriverManager

options = webdriver.EdgeOptions()
options.add_experimental_option("detach", True)
driver = webdriver.Edge(options=options, service=Service(EdgeChromiumDriverManager().install()))
driver.maximize_window()
driver.get('https://stackoverflow.com/questions/68543285/chrome-browser-closes-immediately-after-loading-from-selenium')

For Chrome Browser

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=options, service=Service('./path/to/chromedriver'))
driver.maximize_window()
driver.get('https://stackoverflow.com/questions/68543285/chrome-browser-closes-immediately-after-loading-from-selenium')
Loui
  • 3
  • 1