详解python websocket获取实时数据的几种常见链接方式
发布时间:2020-08-20 01:37:42
来源:脚本之家
阅读:133
作者:Jerry_JD
第一种, 使用create_connection链接,需要pip install websocket-client (此方法不建议使用,链接不稳定,容易断,并且连接很耗时)
import time
from websocket import create_connection
url = 'wss://i.cg.net/wi/ws'
while True: # 一直链接,直到连接上就退出循环
time.sleep(2)
try:
ws = create_connection(url)
print(ws)
break
except Exception as e:
print('连接异常:', e)
continue
while True: # 连接上,退出第一个循环之后,此循环用于一直获取数据
ws.send('{"event":"subscribe", "channel":"btc_usdt.ticker"}')
response = ws.recv()
print(response)
第二种,运行效果很不错,很容易连接,获取数据的速度也挺快
import json
from w