Home > database >  How to kill selenium running as a subprocess?
How to kill selenium running as a subprocess?

Time:11-29

Given the code below, which runs selenium as a multiprocessing.Process. Despite the process being terminated on macOS Ventura 13.0.1, selenium window stays open. Why does the window stay? how to force its termination?

from multiprocessing import Process

from selenium.webdriver import Chrome


def func():
    driver = Chrome()
    driver.get('https://google.com')


if __name__ == '__main__':
    p = Process(target=func)
    p.daemon = True
    p.start()
    p.join(timeout=1)
    if p.is_alive():
        p.terminate()

A current workaround I'm using:

os.system("ps aux | grep Google | awk ' { print $2 } ' | xargs kill -9")

CodePudding user response:

You could do something along these lines:

def func():
    driver = Chrome()
    driver.get('https://google.com')
    driver.quit()

This should close each window, after the function concludes.

See Selenium documentation for more info.

CodePudding user response:

Assuming you are able to modify function func, then pass to it the Chrome driver as an argument instead of it creating the driver itself.

  1. The main process starts a child process, run_selenium that starts func in a daemon thread. It then waits for up to 1 second for func to complete.
  2. If the selenium thread (func) is still alive, a call to stop is made on the underlying driver service. run_selenium then terminates and a long with its daemon func thread.
from threading import Thread
from multiprocessing import Process

from selenium.webdriver import Chrome


def func(driver):
    import time

    # Modified to run forever:
    while True:
        driver.get('https://google.com')
        time.sleep(5)
        driver.get('https://bing.com')
        time.sleep(5)

def run_selenium():
    driver = Chrome()
    # Selenium will terminate when we do:
    t = Thread(target=func, args=(driver,), daemon=True)
    t.start()
    t.join(1)

    # Did selenium actually finish?
    if t.is_alive():
        driver.service.stop()


if __name__ == '__main__':
    p = Process(target=run_selenium)
    p.start()
    p.join()

    print('Selenium terminated; I can now go on to do other things...')
    ...
  • Related