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

如何在Python中检测并复用已打开的Selenium Firefox实例?

复用已运行的Firefox Selenium实例解决方案

1. 正确启动带调试端口的Firefox

打开命令提示符,执行以下命令启动Firefox并开启Marionette调试服务:

cd "C:\Program Files\Mozilla Firefox"
firefox.exe -marionette -start-debugger-server 2828 -no-remote
  • -no-remote:确保调试实例与普通Firefox实例不冲突,避免端口占用问题
  • 无需手动开启marionette.debugging.clicktostart,该选项会要求手动确认连接,易引发超时

2. 复用实例的Python代码

以下代码会先尝试连接已运行的Firefox实例,连接失败则启动新实例:

from selenium import webdriver
from selenium.webdriver.firefox.service import Service
from webdriver_manager.firefox import GeckoDriverManager
import socket

def is_firefox_instance_running(port=2828):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    result = sock.connect_ex(('localhost', port))
    sock.close()
    return result == 0

def get_driver():
    if is_firefox_instance_running():
        # 连接已有的Firefox实例
        driver = webdriver.Remote(
            command_executor='http://localhost:2828',
            options=webdriver.FirefoxOptions()
        )
        return driver
    else:
        # 启动新的Firefox实例并开启调试端口
        firefox_options = webdriver.FirefoxOptions()
        firefox_options.add_argument('-marionette')
        firefox_options.add_argument(f'-start-debugger-server 2828')
        firefox_options.add_argument('-no-remote')
        
        firefox_service = Service(GeckoDriverManager().install())
        driver = webdriver.Firefox(service=firefox_service, options=firefox_options)
        return driver

driver = get_driver()
driver.get('https://stackoverflow.com')

3. 解决TimeoutException问题

你之前遇到的超时错误,核心原因有两个:

  • 使用webdriver.Firefox加--connect-existing参数的方式错误,Selenium 4中复用实例需用webdriver.Remote直接连接调试端口
  • 开启marionette.debugging.clicktostart后需要手动确认连接,导致程序等待超时

注意事项

  • 确保启动Firefox的端口(2828)与代码中使用的端口一致
  • 若需运行多个调试实例,需修改端口号避免冲突
  • 若Firefox实例异常关闭,需确认端口已释放,否则会导致连接失败

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 10:40:30