如何将Selenium 4.31.1连接到已运行的Chrome浏览器
WebDriver执行操作立即断开连接问题修复
我试过的所有代码都已过时,目前找到的所谓最优代码在执行任何WebDriver操作时都会立即断开连接,原代码如下:
from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service import subprocess import os driverPath = ChromeDriverManager().install() subprocess.Popen(["start","chrome","--remote-debugging-port=9089","--user-data-dir=" + os.getcwd() + "/chromeProfile",],shell=True) options = Options() options.add_argument("--start-maximized") options.add_experimental_option("debuggerAddress", "127.0.0.1:9089") service = Service(executable_path=driverPath) driver = webdriver.Chrome(service=service,options=options)
问题分析及修复方案
核心问题
- Chrome未完成初始化就连接:启动Chrome后立刻尝试绑定调试端口,此时Chrome还未完成调试服务的启动,导致连接后直接断开。
- Windows启动命令错误:使用
start命令配合shell=True会导致进程启动逻辑异常,且路径拼接未处理空格场景。 - 用户目录未预创建:Chrome启动时若指定的
user-data-dir不存在,可能引发隐式错误,间接导致连接失败。
修正后的代码
from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service import subprocess import os import time # 处理用户数据目录,自动创建不存在的目录 profile_dir = os.path.join(os.getcwd(), "chromeProfile") os.makedirs(profile_dir, exist_ok=True) # 指定Chrome路径(若系统PATH未包含chrome.exe,需写完整路径,比如"C:/Program Files/Google/Chrome/Application/chrome.exe") chrome_executable = "chrome.exe" # 启动带调试端口的Chrome实例 launch_cmd = [ chrome_executable, "--remote-debugging-port=9089", f"--user-data-dir={profile_dir}", "--start-maximized" ] subprocess.Popen(launch_cmd, shell=False) # 等待Chrome完全启动(根据机器性能调整等待时间,一般2-5秒即可) time.sleep(3) # 配置调试连接参数 options = Options() options.add_experimental_option("debuggerAddress", "127.0.0.1:9089") # 初始化WebDriver service = Service(executable_path=ChromeDriverManager().install()) driver = webdriver.Chrome(service=service, options=options) # 测试操作示例 driver.get("https://www.example.com") print(f"当前页面标题:{driver.title}")
关键修复细节
- 添加启动等待:用
time.sleep()给Chrome留出足够的初始化时间,确保调试端口正常监听后再建立连接。 - 修正启动命令:移除
start命令,直接调用Chrome可执行文件,避免Shell解析带来的进程管理问题;用os.path.join处理路径,兼容带空格的目录。 - 预创建用户目录:通过
os.makedirs()确保指定的用户数据目录存在,避免Chrome启动时的隐式错误。 - 移除重复参数:原代码中
--start-maximized既在启动命令中指定又在Options中添加,属于重复配置,保留一处即可。
内容的提问来源于stack exchange,提问作者Duy Đặng
相关产品推荐
相关产品推荐

