微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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/')
    
    p = psutil.Process(driver.service.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


完。

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐