python3基于websocket搭建webSocket客户端,调用webSocketAPI获取数据

刚开始接触python,由于需要做一个基于webSocketAPI来实时获取数据的功能,记录成长。附上原帖链接:https://segmentfault.com/q/1010000009284816?_ea=1883181   附上源码:

from ws4py.client.threadedclient import WebSocketClient

class DummyClient(WebSocketClient):
    def opened(self):
        self.send("{'event': 'addChannel', 'channel': 'ok_sub_futureusd_btc_ticker_this_week'}") #发送请求数据格式

    def closed(self, code, reason=None):
        print("Closed down", code, reason)

#服务器返回消息
    def received_message(self, m):
        print("recv:", m)


if __name__ == '__main__':
    try:
        # 服务器连接地址wss://real.okex.com:10440/websocket/okexapi  (该地址需,测试可找其他地址)
        ws = DummyClient('wss://real.okex.com:10440/websocket/okexapi', protocols=['chat'])
        ws.connect()
        ws.send("my test...")
        ws.run_forever()
    except KeyboardInterrupt:
        ws.close()

python3基于websocket搭建webSocket客户端,调用webSocketAPI获取数据_第1张图片

原因:是我使用的api需要。

你可能感兴趣的:(python,python爬虫)