使用 Selenium 和 Chrome 远程调试时遇到 WebSocket 连接被远程主机强制关闭的问题

大家好,

我在使用 Selenium 和 Chrome 远程调试功能时遇到了一个问题。我的目标是在 Chrome 浏览器会话中拦截网络请求,但我遇到了一个持续出现的错误。

环境:

  • Python 版本:2023.2.4
  • Selenium 版本4.15.2]
  • Chrome 版本:119.0.6045.160
  • ChromeDriver 版本:你的 ChromeDriver 版本
  • 操作系统:wing11

问题描述: 当我尝试打开一个到 Chrome DevTools 协议的 WebSocket 连接时,连接成功建立,但随即被远程主机关闭,并出现以下错误消息:[WinError 10054] 远程主机强迫关闭了一个现有的连接

以下是我的代码片段:

python 复制代码
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import websocket
import json
import threading
import time
import requests

def on_message(ws, message):
    data = json.loads(message)
    if "method" in data and data["method"] == "Network.requestWillBeSent":
        print("Request URL:", data["params"]["request"]["url"])

def on_error(ws, error):
    print("WebSocket error occurred:", error)

def on_close(ws, status_code, msg):
    print("### WebSocket Closed ###")
    print("Status Code:", status_code)
    print("Message:", msg)

def on_open(ws):
    print("WebSocket connection opened")
    ws.send(json.dumps({"id": 1, "method": "Network.enable"}))

def start_websocket(url):
    ws = websocket.WebSocketApp(url,
                                on_message=on_message,
                                on_error=on_error,
                                on_close=on_close)
    ws.on_open = on_open
    threading.Thread(target=ws.run_forever).start()

chrome_options = Options()
chrome_options.add_argument("--remote-debugging-port=9222")
# 允许来自所有来源的 WebSocket 连接
chrome_options.add_argument("--remote-allow-origins=*")
driver = webdriver.Chrome(options=chrome_options)

driver.get("https://www.baidu.com")  # 修改为你想访问的网址

# 发送HTTP请求到Chrome的远程调试端口
response = requests.get("http://localhost:9222/json")
# 解析响应,获取WebSocket调试器URL
debugger_urls = response.json()
web_socket_url = None
for url in debugger_urls:
    if 'webSocketDebuggerUrl' in url:
        web_socket_url = url['webSocketDebuggerUrl']
        break

if web_socket_url:
    # 使用WebSocket URL开始WebSocket连接
    start_websocket(web_socket_url)
else:
    print("没有找到有效的WebSocketDebuggerUrl")

time.sleep(10)  # 等待 10 秒

driver.quit()  # 关闭浏览器

我已经尝试了以下解决方法,但问题依然存在:

  • 确保没有其他实例占用9222端口
  • 更新了 Chrome 和 ChromeDriver
  • 检查了防火墙和安全软件设置
  • 尝试了不同的网络环境

请问有谁遇到过类似的问题,或者有什么建议吗?非常感谢!

相关推荐
2401_868534786 小时前
长远目标 Long-term Goal 老题沿用
设计模式·需求分析
吃饱了得干活7 小时前
Java设计模式实战:一个支付模块的重构之旅,层层递进理解设计模式精髓
后端·设计模式·架构
vivo互联网技术10 小时前
软件不是从数据开始,而是从现实开始 | KDC 系列 01
设计模式·架构·领域驱动设计
码匠许师傅10 小时前
【设计模式精讲】27.模板方法模式(Template Method)
c++·设计模式·uml·模板方法模式
码匠许师傅13 小时前
【设计模式精讲】28.访问者模式(Visitor)
java·设计模式·访问者模式
码匠许师傅1 天前
【设计模式精讲】26.策略模式(Strategy)
c++·设计模式·策略模式·uml
Ysx1 天前
AI 问答不再"一本正经地胡说":30 轮提示词迭代,沉淀 4 条防幻觉铁律
设计模式
码匠许师傅1 天前
【设计模式精讲】25.状态模式(State)
c++·ui·设计模式·状态模式·uml
geovindu1 天前
java:Observer Pattern
java·开发语言·后端·观察者模式·设计模式·行为模式
码匠许师傅2 天前
【设计模式精讲】24.观察者模式(Observer)
c++·观察者模式·设计模式·uml