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

Selenium能否连接已打开浏览器?验证码验证异常问题求助

用Selenium连接已打开的浏览器实例(解决反爬/验证码问题)

核心思路

通过让浏览器启动时开启远程调试端口,Selenium就能连接到这个已运行的实例,复用手动操作的会话(包括已通过的验证码、登录状态),从根源规避网站对Selenium默认环境的机器人识别。


一、Chrome浏览器实现步骤

1. 手动启动Chrome并开启远程调试

打开命令行(Windows用CMD/PowerShell,Mac/Linux用终端),执行对应命令:

  • Windows:
    chrome.exe --remote-debugging-port=9222 --user-data-dir="C:\selenium\ChromeCustomProfile"
    
  • Mac:
    /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=9222 --user-data-dir="/Users/你的用户名/selenium/ChromeCustomProfile"
    
  • Linux:
    google-chrome --remote-debugging-port=9222 --user-data-dir="/home/你的用户名/selenium/ChromeCustomProfile"
    

说明:--user-data-dir指定自定义用户数据目录,避免和默认浏览器会话冲突,同时保留手动操作的Cookie、验证状态。

2. Python代码连接已启动的Chrome

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

# 配置调试地址,和启动浏览器的端口保持一致
chrome_options = Options()
chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")

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

# 测试:打印当前浏览器的页面URL
print(driver.current_url)
# 后续可直接操作该浏览器,比如点击元素、获取内容

二、Firefox浏览器实现步骤

1. 手动启动Firefox并开启远程调试

方式一:通过浏览器设置开启

  1. 打开Firefox,地址栏输入about:config,点击“接受风险并继续”。
  2. 搜索并修改以下配置:
    • devtools.debugger.remote-enabled → 设置为true
    • devtools.debugger.prompt-connection → 设置为false(避免连接时弹提示)
    • devtools.debugger.port → 设置为9223(自定义端口,可修改)
  3. 重启Firefox。

方式二:命令行启动

# Windows
firefox.exe --start-debugger-server 9223 -profile "C:\selenium\FirefoxCustomProfile"

# Mac
/Applications/Firefox.app/Contents/MacOS/firefox --start-debugger-server 9223 -profile "/Users/你的用户名/selenium/FirefoxCustomProfile"

# Linux
firefox --start-debugger-server 9223 -profile "/home/你的用户名/selenium/FirefoxCustomProfile"

2. Python代码连接已启动的Firefox

from selenium import webdriver
from selenium.webdriver.firefox.options import Options

firefox_options = Options()
firefox_options.add_argument("--remote-debugging-port=9223")

# 连接已打开的Firefox实例
driver = webdriver.Firefox(options=firefox_options)

# 测试:跳转到目标网站(复用已有会话)
driver.get("https://你的目标网站地址")

关键注意事项

  • 端口号必须保持一致:代码中的调试端口要和启动浏览器时指定的端口完全匹配。
  • 自定义用户目录/配置文件必须指定:这是复用会话的核心,能保留你手动完成的验证码验证、登录状态,避免网站识别为新的机器人会话。
  • 规避Selenium特征:连接已打开的浏览器后,Selenium不会注入默认的webdriver标识,网站更难识别你是自动化工具。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 18:23:39