实时抓取网页数据( 小编来一起示例代码介绍-2019年07月01日)

优采云 发布时间: 2021-10-29 16:00

  实时抓取网页数据(

小编来一起示例代码介绍-2019年07月01日)

  详解python websocket获取实时数据的几种常用链接方法

  更新时间:2019-07-01 09:24:16 作者:Jerry_JD

  本文文章主要详细介绍几种常用的从python websocket获取实时数据的链接方式。文章中介绍的示例代码非常详细,对大家的学习或工作有一定的参考学习价值。有需要的朋友在下面和小编一起学习吧

  第一种是使用create_connection链接,需要pip install websocket-client(不推荐这种方法,链接不稳定,容易断,连接耗时)

  

import time

from websocket import create_connection

url = 'wss://i.cg.net/wi/ws'

while True: # 一直链接,直到连接上就退出循环

time.sleep(2)

try:

ws = create_connection(url)

print(ws)

break

except Exception as e:

print('连接异常:', e)

continue

while True: # 连接上,退出第一个循环之后,此循环用于一直获取数据

ws.send('{"event":"subscribe", "channel":"btc_usdt.ticker"}')

response = ws.recv()

print(response)

  第二种,运行效果很好,连接方便,获取数据的速度也很快

  

import json

from ws4py.client.threadedclient import WebSocketClient

class CG_Client(WebSocketClient):

def opened(self):

req = '{"event":"subscribe", "channel":"eth_usdt.deep"}'

self.send(req)

def closed(self, code, reason=None):

print("Closed down:", code, reason)

def received_message(self, resp):

resp = json.loads(str(resp))

data = resp['data']

if type(data) is dict:

ask = data['asks'][0]

print('Ask:', ask)

bid = data['bids'][0]

print('Bid:', bid)

if __name__ == '__main__':

ws = None

try:

ws = CG_Client('wss://i.cg.net/wi/ws')

ws.connect()

ws.run_forever()

except KeyboardInterrupt:

ws.close()

  第三种其实和第一种类似,只是写法不同,运行效果不理想,连接耗时,容易断线

  

import websocket

while True:

ws = websocket.WebSocket()

try:

ws.connect("wss://i.cg.net/wi/ws")

print(ws)

break

except Exception as e:

print('异常:', e)

continue

print('OK')

while True:

req = '{"event":"subscribe", "channel":"btc_usdt.deep"}'

ws.send(req)

resp = ws.recv()

print(resp)

  第四,运行效果也是可以的,run_forever里面的参数很多,需要自己设置

  

import websocket

def on_message(ws, message): # 服务器有数据更新时,主动推送过来的数据

print(message)

def on_error(ws, error): # 程序报错时,就会触发on_error事件

print(error)

def on_close(ws):

print("Connection closed ……")

def on_open(ws): # 连接到服务器之后就会触发on_open事件,这里用于send数据

req = '{"event":"subscribe", "channel":"btc_usdt.deep"}'

print(req)

ws.send(req)

if __name__ == "__main__":

websocket.enableTrace(True)

ws = websocket.WebSocketApp("wss://i.cg.net/wi/ws",

on_message=on_message,

on_error=on_error,

on_close=on_close)

ws.on_open = on_open

ws.run_forever(ping_timeout=30)

  以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

0 个评论

要回复文章请先登录注册


官方客服QQ群

微信人工客服

QQ人工客服


线