您当前的位置: 首页 >  彭世瑜 Python

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

彭世瑜 发布时间:2019-05-09 20:23:27 ,浏览量:2

基本原理

1、实时数据

实时数据
轮询
WebSocket
拉模式 由客户端主动从服务端拉取数据
推模式 由服务端主动将数据推送给客户端

aiowebsocket github:https://github.com/asyncins/aiowebsocket

2、安装:

pip install aiowebsocket
实例

抓取莱特币官网实时数据 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 数据

关注
打赏
1688896170
查看更多评论

彭世瑜

暂无认证

  • 2浏览

    0关注

    2727博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.0552s