无法获取币安WebSocket行情流数据,请求排查代码问题
币安WebSocket无输出问题排查与修复
以下是针对你代码无输出问题的排查方向和修复方案:
1. 新增错误回调捕获异常
原代码没有错误处理逻辑,连接失败、网络中断或协议错误时不会有任何提示,这是最可能导致无输出的核心原因。先给代码加上on_error回调函数,直接打印错误信息:
import websocket import json import pprint SOCKET = "wss://stream.binance.com:9443/ws/ethusdt@kline_1m" def on_open(ws): print('opened connection') def on_close(ws): print('closed connection') def on_message(ws, message): print('received message') json_message = json.loads(message) pprint.pprint(json_message) # 新增错误处理回调,捕获并打印异常 def on_error(ws, error): print(f"error occurred: {error}") ws = websocket.WebSocketApp( SOCKET, on_open=on_open, on_close=on_close, on_message=on_message, on_error=on_error # 绑定错误回调 ) ws.run_forever()
2. 确认依赖库安装正确
你可能安装了重名的错误包:
- 卸载错误的包:
pip uninstall websocket - 安装官方指定的客户端:
pip install websocket-client
注意:websocket和websocket-client是两个完全不同的包,前者并非用于连接币安这类公共WebSocket服务的客户端。
3. 检查网络连通性
如果添加错误回调后提示连接超时,说明你的网络环境无法访问币安的WebSocket节点:
- 先尝试用浏览器访问
wss://stream.binance.com:9443/ws/ethusdt@kline_1m(部分浏览器支持直接打开WebSocket链接),确认是否能建立连接。 - 若处于代理环境,需要给
run_forever()添加代理参数,示例:ws.run_forever(proxy_type="http", http_proxy_host="你的代理IP", http_proxy_port=你的代理端口)
内容的提问来源于stack exchange,提问作者useeeeer132
相关产品推荐
相关产品推荐

