Python爬虫:利用aiowebsocket库抓取WebSocket数据

基本原理
1、实时数据

实时数据
轮询
WebSocket
拉模式 由客户端主动从服务端拉取数据
推模式 由服务端主动将数据推送给客户端
aiowebsocket github:https://github.com/asyncins/aiowebsocket

2、安装:

pip install aiowebsocket
1
实例
抓取莱特币官网实时数据 http://www.laiteb.com/

刷新页面观察请求
WebSocket 地址为:wss://api.bbxapp.vip/v1/ifcontract/realTime

1、数据交互模式为:

2、代码实例

# -*- coding: utf-8 -*-

import asyncio
from aiowebsocket.converses import AioWebSocket


async 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 数据

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。