Python中如何使用selenium attach到一个已经打开的浏览器页面上?

我搜索了一下使用了一下的代码, 但是提示由于目标计算机积 极拒绝,无法连接. 不知道各位有没有类似的经历, 实际上我觉得如果能 attach 在已经打开的浏览器上更加的实用。

# -*- coding: utf-8 -*-
from selenium import webdriver
import time
import json
import traceback
import sys
import os
from urllib import request
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.chrome.options import Options

driver = webdriver.Chrome() #python url = driver.command_executor._url #“http://127.0.0.1:60622/hub” print(url) session_id = driver.session_id #‘4e167f26-dc1d-4f51-a207-f761eaf73c31’ driver = webdriver.Remote(command_executor=url,desired_capabilities={}) driver.session_id = session_id driver.get(“http://www.baidu.com”)


Python中如何使用selenium attach到一个已经打开的浏览器页面上?

1 回复

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

# 配置Chrome调试端口
chrome_options = Options()
chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")

# 连接到已打开的浏览器
driver = webdriver.Chrome(options=chrome_options)

# 现在可以操作已打开的页面了
print("当前标题:", driver.title)

关键步骤:

  1. 启动Chrome时开启调试端口(在终端执行):
chrome.exe --remote-debugging-port=9222 --user-data-dir="C:\temp\chrome_profile"

或者用Chrome路径:

"C:\Program Files\Google\Chrome\Application\chrome.exe" --remote-debugging-port=9222
  1. Python代码连接:使用debuggerAddress参数指向同一个端口。

注意事项:

  • 确保端口号一致(示例用9222)
  • 首次运行需要手动打开Chrome并登录(如有需要)
  • 多个标签页时默认连接第一个,可用driver.window_handles切换

一句话建议: 先开调试端口再写代码连接。

回到顶部