When finishing the script with "Ctrl+C" (KeyboardInterrupt) does not close Selenium Firefox
-
I'm using the selenium to manipulate a page, when running the script it opens the firefox, but what I wanted to do is the following, if any problem happens in the script or if the user finishes, I want the firefox to close too.
I tried various things like:
Use the exit:
def __exit__(self): self.fechaAba()
Or the del:
def __del__(self): self.fechaAba()
The function I'm using is this, it's working, I use it in the exceptions to close the firefox when the error.
def fechaAba(self): try: self.__driver.driver.close() except: setLog("Firefox ja finalizado")
But for example if it tightens Ctrl + C to finish the script it does not close the firefox, the closest I got was using the atexit:
import atexit
def __init__(self): atexit.register(self.exit_handler) def exit_handler(self): self.fechaAba()
It presents the message "Firefox already finished", but firefox remains open:
KeyboardInterrupt
[2017-09-28 15:16:41]: Firefox ja finalizado
[2017-09-28 15:16:42]: Firefox ja finalizado
When I use the driver.close() it enters the exception and presents the message "Firefox already finished", i.e. it failed to execute the command, and when I use quit the effect is similar, it usually performs the quit(Does not enter the exception), but the firefox remains open.
I made a small example:
from selenium import webdriver
import time
import atexitclass WhatsappAPI(object):
driver = None def __init__(self): print "__init__" atexit.register(self.exit_handler) self.driver = webdriver.Firefox() self.driver.get("http://web.whatsapp.com") def comeca_acao(self): while True: time.sleep(10) print "ok" def exit_handler(self): print "exit_handler" self.driver.quit() def __exit__(self): print "__exit__" self.driver.quit() def __del__(self): print "__del__" self.driver.quit()
w = WhatsappAPI()
w.comeca_acao()
Result:
teste.py
init
Traceback (most recent call last):
File "C:\Users\Futurotec\Documents\futurofone_chat\branch\v3.12_externo\WhatsappBot - Instalador\Final\WhatsappWebAPI\teste.py", line 34, in <module>
w.comeca_acao()
File "C:\Users\Futurotec\Documents\futurofone_chat\branch\v3.12_externo\WhatsappBot - Instalador\Final\WhatsappWebAPI\teste.py", line 17, in comeca_acao
time.sleep(10)
KeyboardInterrupt
exit_handler
del
When it appears in the terminal "
init
" it opens firefox, when ctrl grip c the firefox continues open, what I want is that firefox closes to ctrl tightening c or when entering any exception. In exceptions it already works, but when ctrl tightening c not.
-
Try treating the KeyboardInterrupt exception when running the program, e.g.
try: w = WhatsappAPI() w.comeca_acao() except KeyboardInterrupt: w.driver.quit() print "Ate logo!"