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

使用GeckoDriver通过Selenium连接已有Firefox窗口失败求助

复用已有Firefox实例实现内存高效的Python Selenium脚本

要实现复用单个Firefox实例以降低内存占用、提升执行效率,你之前尝试的--connect-existing参数已被淘汰,正确的做法是通过远程调试端口绑定已有实例,具体步骤如下:

1. 手动启动带调试端口的Firefox实例

先关闭所有正在运行的Firefox进程,然后通过终端/命令行启动Firefox并指定调试端口:

# Windows(根据你的Firefox安装路径调整)
"C:\Program Files\Mozilla Firefox\firefox.exe" -remote-debugging-port=9222

# Linux/macOS
firefox --remote-debugging-port=9222

启动后Firefox会保持运行状态,后续所有脚本都将连接这个实例。

2. 编写Python脚本连接已有实例

在脚本中配置FirefoxOptions指向调试端口,驱动会自动连接已启动的Firefox,而非新建窗口:

from selenium import webdriver
from selenium.webdriver.firefox.options import Options

options = Options()
# 匹配启动时指定的调试端口
options.add_argument("--remote-debugging-port=9222")
# 禁用首次运行和默认浏览器检查,避免干扰脚本执行
options.add_argument("--no-first-run")
options.add_argument("--no-default-browser-check")

# 初始化驱动,连接已有Firefox实例
driver = webdriver.Firefox(options=options)

# 示例操作:打开网页并打印标题
driver.get("https://www.example.com")
print(driver.title)

# 若需新建标签页,使用以下方式(不会新建窗口)
driver.switch_to.new_window('tab')
driver.get("https://www.google.com")

关键注意事项

  • 不要在脚本中调用driver.quit(),否则会直接关闭整个Firefox实例;仅关闭当前标签页用driver.close()
  • 所有需要复用实例的脚本必须使用相同的调试端口
  • 确保启动Firefox时没有其他进程占用指定的调试端口

内容的提问来源于stack exchange,提问作者code-0101

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 06:20:21