Home > Software engineering >  Keeping Selenium browser open after python script completion
Keeping Selenium browser open after python script completion

Time:12-28

I'm working on a selenium project, but every time the script ends, the window automatically closes. I'd like to keep the window up, though, after the script closes. I've googled this, and stackoverflow says to uses the following code to keep it open:

chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option("detach", True)
s = Service(CHROME_DRIVER_PATH)
driver = webdriver.Chrome(options = chrome_options,service=s)
driver.get(URL)

I've tried using this, but it doesn't work - the window still automatically closes as soon as the script ends. In fact I looked on the Chromedriver docs and it specifically says that using the detach option will still close the browser after the session is quit. I want to be able to keep the window open so that I can use the developer console to figure the next tags I need to code in for my script. (ie, I have the script open a page for me, sign in for me, then I need to do actions after I sign in). Has anyone else here dealt with this or tried to do this? Having this browser closing on me is driving me nuts!! Yeah I could open the page in another instantiation of the browser but I don't want to do that. I could use a while True at the end of my script or have the script sleep for a thousand seconds or something, but that's inelegant and not the right way to go about it...

CodePudding user response:

please try as following:

from selenium import webdriver

ch_options=webdriver.ChromeOptions()
driver=webdriver.Chrome(executable_path=r'C:\chromedriver\chromedriver.exe',options=ch_options)
driver.get('https://www.google.com/?hl=es')

CodePudding user response:

If this is only for development or debugging, maybe you can add an input command as this will keep the webdriver running until you call webdriver.quit() and then end the script. Here is an example:

# selenium code goes here
keyword = input("enter a character or press enter to continue")
webdriver.quit()

using time.sleep() will run out of time and basically you can't control when it will stop or if it takes too long.

  • Related