如何杀死Selenium作为一个子过程运行



给定下面的代码,它将selenium作为multiprocessing.Process运行。尽管macOS Ventura13.0.1上的进程已终止,但硒窗口仍处于打开状态。为什么窗户一直开着?如何强制终止?

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()

我正在使用的当前解决方法:

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

您可以按照以下方式进行操作:

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

这应该会在函数结束后关闭每个窗口。

有关更多信息,请参阅Selenium文档。

假设您能够修改函数func,那么将Chrome驱动程序作为参数传递给它,而不是它自己创建驱动程序。

  1. 主进程启动一个子进程run_selenium,该进程在守护进程线程中启动func。然后,它等待长达1秒的func完成
  2. 如果硒线程(func)仍处于活动状态,则在底层驱动程序服务上调用stop。然后CCD_ 9终止并与其守护进程CCD_
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...')
...

最新更新