如何为Undetected Chromedriver设置调试端口并连接现有会话?
用Undetected Chromedriver实现会话复用调试
步骤1:启动带固定调试端口的Undetected Chromedriver会话
要让undetected-chromedriver支持远程调试,必须显式传入调试端口参数,同时指定用户数据目录确保会话状态持久化:
import undetected_chromedriver as uc from selenium.webdriver.chrome.service import Service options = uc.ChromeOptions() # 设置远程调试端口 options.add_argument("--remote-debugging-port=50620") # 指定用户数据目录,避免每次启动临时配置 options.add_argument(r"--user-data-dir=C:\chromedriver\chromeProfile") # 初始化驱动 driver = uc.Chrome( options=options, service=Service(r"C:\chromedriver\chromedriver.exe") ) print("会话已启动,调试端口:50620")
步骤2:连接已有的Undetected Chromedriver会话
连接时不要使用uc.Chrome(),改用标准Selenium的Chrome驱动,否则会强制启动新会话:
from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service options = Options() # 指定要连接的调试端口 options.add_experimental_option("debuggerAddress", "localhost:50620") # 连接到已运行的会话 driver = webdriver.Chrome( service=Service(r"C:\chromedriver\chromedriver.exe"), options=options ) # 验证连接成功 print("连接成功,当前页面标题:", driver.title)
核心注意点
- 初始化会话时必须显式添加
--remote-debugging-port参数,undetected-chromedriver不会默认保留该配置。 - 连接会话必须使用标准
webdriver.Chrome(),uc.Chrome()会自动修改端口和配置,导致无法复用已有会话。 - 确保指定的调试端口未被其他程序占用,否则初始化会失败。
- 指定
user-data-dir可以保留浏览器的Cookie、缓存等状态,进一步提升调试效率。
该方案完全实现了原有普通ChromeDriver的功能:启动一次会话后,后续调试代码直接连接,无需重复启动Chrome,跳过初始页面加载,专注于目标元素调试。
内容的提问来源于stack exchange,提问作者M Bala
相关产品推荐
相关产品推荐

