如何使用Selenium 4操控已存在的浏览器会话?
Selenium 4 操控已有浏览器会话的可行方案
一、Chrome浏览器操作步骤
- 启动带调试端口的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
启动后可正常操作浏览器(如登录目标网站、打开指定页面)。
- 用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浏览器操作步骤
- 启动带远程控制的Firefox会话
关闭所有Firefox进程,通过命令行启动并开启Marionette与调试端口:
firefox --marionette --remote-debugging-port=9223
- 用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
相关产品推荐
相关产品推荐

