python之WebSocket通信爬虫协议请求方法

一、请求方法

import websocket
import _thread as thread
import time

def on_message(ws, message):
    """收到对方消息处理方法"""
    print("对方发来的消息:",message)
    time.sleep(5)   # 控制发送频率
    ws.send('ping')        # 我方决定再回一个消息

def on_error(ws, error):
    """ 错误处理方法 """
    print(error)

def on_close(ws,code,msg):
    """ 关闭处理方法 """
    print("代号:",code)
    print("对方关闭发来的消息:", msg)
    print("### 程序结束 ###")

def on_open(ws):
    """ 运行入口 """
    def run(*args):
        ws.send('ping')    # 我方发送第一个消息
    thread.start_new_thread(run, ())   # 开启线程

header = ['GET /chat HTTP/1.1', 'X-CHAIN-ID: 0xf935a612f5914f337e044e37a180e7e04f2cba5c', 'X-NETWORK-VERSION: devnet__1.0',
               'X-SESSION-ID: 33464828-9752-4f5a-8d97-c2000351e32a', 'X-USER-IP: 113.65.21.75', 'X-DEVICE-ID: ',
               'X-APP-VERSION: 50', 'X-DEVICE-OS: 28',
               'X-DEVICE-MODEL: V1809T', 'X-DEVICE-LOCATION: ',
               'X-DEVICE-MANUFACTURER: vivo', 'Upgrade: websocket', 'Connection: Upgrade','Sec-WebSocket-Key: YapnL6tlenDwlqP/qsXUhA==','Sec-WebSocket-Version: 13',
               'Sec-WebSocket-Extensions: permessage-deflate','Host: devnet.gravitychain.network','Accept-Encoding: gzip','User-Agent: okhttp/4.11.0']

# websocket.enableTrace(True)    # 是否打开日志信息
ws = websocket.WebSocketApp("wss://devnet.gravitychain.network/chat",
                            header=header,       # 设置请求头
                            on_open=on_open,     # 设置运行入口
                            on_message=on_message,   # 设置收到消息处理
                            on_close=on_close,  # 发生关闭处理
                            on_error=on_error,    # 错误处理
                            )

ws.run_forever()




你可能感兴趣的:(python,websocket,爬虫)