2

In my program I got something like this:

driver = webdriver.Chrome(options=Options()) #calling the driver
driver.get(website) #opening the website
try:
    while True:
        do_something() #Here I do a couple of things
except KeyboardInterrupt: 
    #When I'm done with the while loop above(the goal is to be able to stop at any point of the loop) I use ctrl+c
    pass
#Here the program continues but selenium closes the window even though I didn't call for driver.quit().

While it successfully stops the while loop and don't end the program itself, selenium closes the window browser. Is there a way to prevent selenium from closing the window?

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
hazboin
  • 21
  • 3
  • Selenium will not close the browser if you did not tell it to do so. We'll need to see more of your code. –  Feb 02 '21 at 17:38
  • Sorry, I edited the original post and added more information. The point is that I want to successfully leave the while loop at any point. I achieved that with ctrl+c but that closes the window browser as well and I would like to keep that open. – hazboin Feb 02 '21 at 17:51
  • Hmm... See https://stackoverflow.com/questions/46135888/python-selenium-ctrlc-closes-chromedriver –  Feb 02 '21 at 18:00
  • I tried that but for some reason it doesn't even open a browser and crashes right after. – hazboin Feb 02 '21 at 18:22
  • What do you mean under "I want to successfully leave the while loop at any point", do you have specific condition, or end while randomly – Gaj Julije Feb 02 '21 at 20:17

1 Answers1

1

When you are done with the while loop instead of using ctrl + C you can easily break out as follows:

from selenium.common.exceptions import NoSuchElementException, TimeoutException, WebDriverException

driver = webdriver.Chrome(options=Options()) #calling the driver
driver.get(website) #opening the website
while True:
    try:
        do_something() #Here I do a couple of things
    except (NoSuchElementException, WebDriverException, TimeoutException):
        break
# Here the program continues and selenium doesn't closes the window even
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352