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

如何使用Python/Selenium/Firefox获取WebDriver进程PID?

获取Selenium Firefox WebDriver/浏览器进程PID的解决方案

你遇到的问题是因为当前使用的Selenium版本中,FirefoxBinary对象并没有直接暴露process属性,所以调用driver.binary.process.pid会抛出属性错误。下面给你几种可行的解决办法,根据你需要的是GeckoDriver驱动进程的PID还是Firefox浏览器进程的PID来选择:

方法一:获取GeckoDriver驱动的PID

如果你需要的是控制浏览器的GeckoDriver进程PID,可以直接通过Selenium的service对象获取,这是最直接的方式:

from selenium import webdriver
# 如果你用的是Selenium 4+,建议用Service类配置驱动路径
from selenium.webdriver.firefox.service import Service

# Selenium 4+的写法(推荐)
service = Service(executable_path=pathToFF)
driver = webdriver.Firefox(service=service, firefox_binary=pathToBinaries, options=opts)
geckodriver_pid = service.pid

# 旧版Selenium写法
# driver = webdriver.Firefox(executable_path=pathToFF, firefox_binary=pathToBinaries, firefox_options=opts)
# geckodriver_pid = driver.service.pid

print(f"GeckoDriver进程PID: {geckodriver_pid}")

方法二:获取Firefox浏览器进程的PID

如果你的目标是获取Firefox浏览器本身的进程PID,可以结合psutil工具来查找和GeckoDriver关联的浏览器进程:

首先确保服务器上安装了psutil:

pip install psutil

然后使用以下代码:

import psutil
from selenium import webdriver
from selenium.webdriver.firefox.service import Service

# 初始化driver
service = Service(executable_path=pathToFF)
driver = webdriver.Firefox(service=service, firefox_binary=pathToBinaries, options=opts)
geckodriver_pid = service.pid

# 查找GeckoDriver的子进程中的Firefox进程
geckodriver_proc = psutil.Process(geckodriver_pid)
# 不同系统下Firefox进程名可能不同,Linux是firefox,Windows是firefox.exe,macOS可能是Firefox
firefox_procs = [
    proc for proc in geckodriver_proc.children(recursive=True)
    if proc.name().lower().startswith("firefox")
]

if firefox_procs:
    firefox_pid = firefox_procs[0].pid
    print(f"Firefox浏览器进程PID: {firefox_pid}")
else:
    print("未找到关联的Firefox浏览器进程")

额外说明

  • 如果你使用的是非常旧的Selenium版本,可能尝试等待浏览器完全启动后再访问driver.binary.process,但这种方式可靠性较低,不如上面的方法稳定。
  • 在服务器环境下运行时,确保脚本有足够的权限访问进程信息(避免权限不足导致psutil无法获取进程列表)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:41:45