I initiated and close phantomjs in Python with the following

from selenium import webdriver    
driver = webdriver.PhantomJS()
driver.get(url)
html_doc = driver.page_source
driver.close()

yet after the script ends execution I still find an instance of phantomjs in my Mac Activity Monitor. And actually every time I run the script a new process phantomjs is created.

How should I close the driver?


As of July 2016, driver.close() and driver.quit() weren't sufficient for me. That killed the node process but not the phantomjs child process it spawned.

Following the discussion on this GitHub issue, the single solution that worked for me was to run:

import signal

driver.service.process.send_signal(signal.SIGTERM) # kill the specific phantomjs child proc
driver.quit()                                      # quit the node proc

Please note that this will obviously cause trouble if you have several threads/processes starting PhantomJS on your machine.

I've seen several people struggle with the same issue, but for me, the simplest workaround/hack was to execute the following from the command line through Python AFTER you have invoked driver.close() or driver.quit():

pgrep phantomjs | xargs kill

The .close() method is not guaranteed to release all resources associated with a driver instance. Note that these resources include, but may not be limited to, the driver executable (PhantomJS, in this case). The .quit() method is designed to free all resources of a driver, including exiting the executable process.


I was having a similar issue on Windows machine. I had no luck with either

driver.close()

or

driver.quit()

actually closing out of the PhantomJS window, but when I used both, the PhantomJS window finally closed and exited properly.

driver.close()
driver.quit()

driver.quit() did not work for me on Windows 10, so I ended up adding the following line right after calling driver.close():

os.system('taskkill /f /im phantomjs.exe')

where

/f = force
/im = by image name

And since this is a Windows only solution, it may be wise to only execute if os.name == 'nt'