这里的业余爱好编码员正在做一个周末项目。
我希望访问此处显示的公开可用 API:https://api.coinsecure.in/ 它为我们提供了比特币交易数据——API 是通过我不熟悉的 websockets 实现的。
Websocket URI 是 wss://coinsecure.in/websocket 我想测试的方法是:{"method": "recentbuytrades"}
我可以使用 Python 中的“websocket-client”访问 WebScocket 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()
最佳答案
试试这个:
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 是无限连接;信息经常不止一次地通过它们发送。您将从服务器(看起来像 JSON)获取一堆信息(“帧”),处理它,然后等待下一批信息的到来。
API 似乎也会向您发送您不一定需要的数据。如果框架不包含 recentbuytrades
键,您可能希望将其丢弃。
关于python - 使用 Python 通过 WebSockets 访问 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35105485/