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

如何使用Selenium 4操控已存在的浏览器会话?

Selenium 4 操控已有浏览器会话的可行方案

一、Chrome浏览器操作步骤

  1. 启动带调试端口的Chrome会话
    关闭所有正在运行的Chrome进程,通过命令行启动浏览器并开启远程调试端口:
  • Windows系统:chrome.exe --remote-debugging-port=9222
  • Mac系统:/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=9222
  • Linux系统:google-chrome --remote-debugging-port=9222
    启动后可正常操作浏览器(如登录目标网站、打开指定页面)。
  1. 用Selenium 4连接已有会话
    通过ChromeOptions指定调试地址,示例Python代码:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By

options = Options()
# 指定已启动浏览器的调试地址
options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")
# 初始化驱动,连接已有会话
driver = webdriver.Chrome(options=options)

# 验证连接:打印当前页面标题
print(driver.title)
# 后续可执行任意操控操作,比如点击元素
# driver.find_element(By.CSS_SELECTOR, ".target-btn").click()

二、Firefox浏览器操作步骤

  1. 启动带远程控制的Firefox会话
    关闭所有Firefox进程,通过命令行启动并开启Marionette与调试端口:
firefox --marionette --remote-debugging-port=9223
  1. 用Selenium 4连接已有会话
    示例Python代码:
from selenium import webdriver
from selenium.webdriver.firefox.options import Options

options = Options()
options.add_argument("--marionette")
options.add_argument("--remote-debugging-port=9223")
driver = webdriver.Firefox(options=options)

# 执行操控操作
print(driver.current_url)

注意事项

  • 确保调试端口未被其他程序占用,可更换未使用的端口号(如9224)
  • Selenium 4版本需与浏览器版本兼容,避免出现连接失败或功能异常
  • 若连接远程机器上的浏览器,需将debuggerAddress替换为对应机器的IP和端口,同时确保防火墙允许该端口的通信

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 00:41:58