You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Karate框架中每次实例执行后终止Chrome Driver进程

自动化终止残留Chrome Driver进程的方案

按操作系统分类的脚本实现

  • Windows 平台
    使用PowerShell命令直接清理:

    Get-Process -Name chromedriver -ErrorAction SilentlyContinue | Stop-Process -Force
    

    若要集成到Python测试脚本中:

    import subprocess
    subprocess.run(["powershell", "-Command", "Get-Process -Name chromedriver -ErrorAction SilentlyContinue | Stop-Process -Force"], check=False)
    
  • Linux/macOS 平台
    最简清理命令:

    pkill -f chromedriver
    

    更严谨的版本(避免误杀同名非目标进程):

    ps aux | grep chromedriver | grep -v grep | awk '{print $2}' | xargs kill -9
    

    集成到Python脚本:

    import subprocess
    subprocess.run(["pkill", "-f", "chromedriver"], check=False)
    

测试框架内的兜底处理

在测试代码中加入try-finally块,确保无论测试成功/失败,都能清理进程:

from selenium import webdriver
import subprocess
import os

def clean_chromedriver():
    if os.name == 'nt':
        subprocess.run(["powershell", "-Command", "Get-Process -Name chromedriver -ErrorAction SilentlyContinue | Stop-Process -Force"], check=False)
    else:
        subprocess.run(["pkill", "-f", "chromedriver"], check=False)

try:
    driver = webdriver.Chrome()
    # 你的测试逻辑代码
    driver.get("你的目标URL")
finally:
    # 先尝试正常退出Driver
    try:
        driver.quit()
    except Exception:
        pass
    # 兜底清理残留进程
    clean_chromedriver()

补充说明

残留进程通常是因为测试异常中断时,driver.quit()未被执行导致的。上述兜底脚本可以确保所有Chrome Driver实例被强制终止,避免影响后续测试执行。

内容的提问来源于stack exchange,提问作者Boopathi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 19:57:18