10
I am using Selenium to manipulate a page, while running the script it opens firefox, but what I wanted to do is this, if any problem in the script or if the user finishes, I want firefox to close as well.
I tried a lot of 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 firefox when the error.
def fechaAba(self):
try:
self.__driver.driver.close()
except:
setLog("Firefox ja finalizado")
But for example if I press Ctrl+C to finish the script it does not close firefox, the closest I got was using 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.close() driver it enters the Exception and displays the "Firefox already finished" message, that is to say it failed to run the command, and when I use quit the effect is similar, it normally runs quit(Does not enter Exception), but firefox remains open.
I made a small example:
from selenium import webdriver
import time
import atexit
class 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()
Upshot:
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 c hit the firefox remains open, what I want is for firefox to close when press Ctrl c or when entering any Exception. In the exceptions it already works, but when I tighten Ctrl c no.
After tests I realized that the problem really seems to be either with Sellenium or with geckodriver (probably only occurs in Windows, but I can’t say). I’m trying to create to bypass. + 1 because doubt will be very useful for many visitors.
– Guilherme Nascimento
try to use the Pyinput library to check the sequence of keystrokes pressed, if positive for "Cltr+C" you use the webdriver.quit() | quit.()
– Ivison Vergasta