python selenium 关闭命令窗口时,自动关闭浏览器
本文地址:https://www.cnblogs.com/tujia/p/15434596.html
接上一篇:python 捕获命令窗口终结信号并处理(event handler) - Tiac - 博客园 (cnblogs.com)
问题:
当前使用 selenium 并加了阻塞的情况下,如果使用的是 firefox 浏览器,quit() 方法不太好使(chrome 没问题)
解决办法:
quit() 方法不好使的话,只好使用 taskkill 来杀进程了
代码:
import os import time import psutil import win32api from selenium import webdriver processes = [] def register_exit_handler(signum): if signum in [0, 2]: print('关闭程序中, 请稍候...') command = 'taskkill' for pid in processes: command += ' /pid %s' % pid os.system(command) time.sleep(2) exit(0) def run(): driver = webdriver.Firefox(executable_path='./geckodriver.exe') driver.get('https://www.baidu.com/') pid = driver.service.process.pid processes.append(pid) p = psutil.Process(pid) for x in p.children(recursive=True): processes.append(x.pid) win32api.SetConsoleCtrlHandler(register_exit_handler, True) print('running...') while True: pass if __name__ == '__main__': run()
本文地址:https://www.cnblogs.com/tujia/p/15434596.html
完。