使用Python通过WebSockets访问API

2024-10-01 15:30:12 发布

您现在位置:Python中文网/ 问答频道 /正文

业余爱好编码器在这里工作的一个周末项目。在

我希望访问一个公开可用的API,如下所示:https://api.coinsecure.in/ 它为我们提供比特币交易数据——API是通过我不熟悉的websockets实现的。在

Websocket URI是wss://coinsecure.in/websocket 我想测试的方法是:{“method”:“recentbuytrades”}

我能够使用Python中的“websocket client”访问webcocket API,如下所示:https://pypi.python.org/pypi/websocket-client/

但不幸的是,我无法找出如何检索特定方法的数据{“method”:“recentbuytrades”}

非常感谢您能为这个特定方法提取数据提供任何指导。在

最好的, 瑞安

[编辑] 我使用的当前代码是:

from websocket import create_connection
ws = create_connection("wss://coinsecure.in/websocket")
result =  ws.recv()
print ("Received '%s'" % result)
ws.close()

Tags: 数据方法inhttpspypiclientapiws
1条回答
网友
1楼 · 发布于 2024-10-01 15:30:12

试试这个:

from websocket import create_connection
ws = create_connection("wss://coinsecure.in/websocket")
ws.send('{"method": "recentbuytrades"}')

while True:
  result =  ws.recv()
  print ("Received '%s'" % result)

ws.close()

注意ws.send()方法,它告诉API您想要什么。接下来,while True无限循环websocket是不确定的连接;信息通常通过它们多次发送。在这里,您将从服务器获得一组信息(一个“frame”),处理它,然后等待下一组信息出现。在

看起来API也会向你发送你不需要的数据。如果帧不包含recentbuytrades键,则可能需要将其抛出。在

相关问题 更多 >

    热门问题