有两种方式可以实现实时数据获取,第一种是定时的执行一次脚本,抓取服务端的数据,
这种方式并不能真正的实时抓取,因为它有一定的时间间隔,
第二种方式是由服务器主动的推送数据,这种方式是实时的。
下面就用aiowebsocket来实现以下吧
拉模式 由客户端主动从服务端拉取数据
推模式 由服务端主动将数据推送给客户端
aiowebsocket github:https://github.com/asyncins/aiowebsocket
2、安装:
pip install aiowebsocket
刷新页面观察请求 WebSocket 地址为:wss://api.bbxapp.vip/v1/ifcontract/realTime
1、数据交互模式为:
2、代码实例
# -*- coding: utf-8 -*-import asynciofrom aiowebsocket.converses import AioWebSocketasync def startup(uri): async with AioWebSocket(uri) as aws: converse = aws.manipulator # 给服务端发送验证消息,观察网页接口数据动态获取 message = '{"action":"subscribe","args":["QuoteBin5m:14"]}' await converse.send(message) while True:receive = await converse.receive()# 拿到的是byte类型数据,解码为字符串数据print(receive.decode())if __name__ == '__main__': remote = 'wss://api.bbxapp.vip/v1/ifcontract/realTime' asyncio.get_event_loop().run_until_complete(startup(remote))
3、数据效果
参考: Python 如何爬取实时变化的 WebSocket 数据
我的博客即将同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=1bzzomxupiicv