hazboin
hazboin

Reputation: 31

Selenium is there a way to prevent ctrl+c to close browser window

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?

Upvotes: 3

Views: 1663

Answers (2)

mfrnd
mfrnd

Reputation: 11

When the Chrome process is created in the same process group as its parent process, Chrome also receives the SIGINT. To prevent that behavior, Chrome needs to be spawned in a separate process group.

See the answer by ryyyn to How can I make CTRL+C interrupt the script without closing Selenium WebDriver?.

Posting this an answer since I lack the points for commenting / flagging as duplicate.

Upvotes: 1

undetected Selenium
undetected Selenium

Reputation: 193298

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

Upvotes: 2

Related Questions