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

Python Selenium Firefox调用driver.quit()无法清理/tmp临时文件求助

问题原因说明

你遇到的/tmp目录临时文件残留问题和代码中的点击操作没有任何关系,是Selenium 3.8.0 + GeckoDriver 0.29 + Firefox 80这个版本组合的已知缺陷:驱动执行driver.quit()时的临时目录清理逻辑存在bug,导致每次启动浏览器实例生成的临时配置文件目录没有被正确删除,和你执行的页面操作无关。

解决方案

方案1:彻底解决临时文件残留问题

有两种可行的版本调整方式:

  • 升级Selenium到4.x版本,适配当前的GeckoDriver 0.29和Firefox 80,修复退出清理逻辑的bug
  • 若不想升级Selenium,将GeckoDriver降级到0.28版本,和你当前的Selenium 3.8.0、Firefox 80匹配,也能解决残留问题

如果不方便调整版本,可以在代码中driver.quit()执行后增加手动清理逻辑:

import os
import shutil

tmp_root = "/tmp"
# 匹配Selenium+Firefox生成的临时目录前缀
target_prefixes = ("rust_mozprofile", "tmp", "Temp_")

for entry in os.listdir(tmp_root):
    entry_path = os.path.join(tmp_root, entry)
    if entry.startswith(target_prefixes) and os.path.isdir(entry_path):
        try:
            shutil.rmtree(entry_path)
        except OSError:
            # 跳过正在被其他进程占用的目录,避免误删
            continue

方案2:重定向临时文件生成路径(备选)

如果需要保留现有版本,也可以将Selenium生成的临时文件定向到自定义目录,避免占满根目录下的/tmp,有两种实现方式:

方式1:修改运行时的临时目录环境变量

先创建你指定的临时目录,比如/data/selenium_tmp,启动脚本前指定TMPDIR环境变量即可:

mkdir -p /data/selenium_tmp
export TMPDIR=/data/selenium_tmp && python 你的脚本名称.py

所有临时文件都会生成到你指定的/data/selenium_tmp目录下,按需定期清空即可。

方式2:代码中显式指定Firefox配置文件路径

直接在初始化浏览器时指定自定义的配置文件存放目录,代码示例:

import os
import tempfile
import shutil
from selenium import webdriver
from selenium.webdriver.firefox.options import FirefoxOptions

# 自定义临时文件根目录
custom_tmp_root = "/data/selenium_tmp"
os.makedirs(custom_tmp_root, exist_ok=True)

# 生成实例专属的配置目录
profile_path = tempfile.mkdtemp(dir=custom_tmp_root)
opts = FirefoxOptions()
opts.add_argument("--headless")
opts.add_argument(f"--profile={profile_path}")

# 初始化驱动
driver = webdriver.Firefox(executable_path=firefox_driver_path, options=opts)

# 你的业务逻辑
# ...

driver.quit()
# 执行完直接删除当前实例的临时目录
shutil.rmtree(profile_path)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 10:06:03