websocket反爬

'''
websocket反爬 4.5
抓取乐鱼体育
1、获取token
2、构建message
3、websocket长连接
'''
from common.tools import Tool
import requests
import json
import time
import websocket

class LeYu:
    def __init__(self):
        self.tool = Tool.get_tool()

    def get_cookie(self):
        url = 'https://live.611.com/Live/GetToken'
        headers = {}
        headers = self.tool.get_user_agent(headers)
        r = requests.get(url=url, headers=headers)
        token = json.loads(r.text).get('Data')
        if token:
            return True, token
        else:
            return False, ''

    def get_message(self):
        message1 = {"command": "RegisterInfo", "action": "Web", "ids": [], "UserInfo": {
            "Version": "[{}]".format(int(round(time.time() * 1000)))+"{\"chrome\":true,\"version\":\"74.0.3729.108\",\"webkit\":true}",
            "Url": "https://live.611.com/lq"}}
        message2 = {"command":"JoinGroup","action":"BasketSoccerLive","ids":[]}
        message3 = {"command":"JoinGroup","action":"BtbLiveOdd","ids":[]}
        return json.dumps(message1),json.dumps(message2),json.dumps(message3)

    def connect_websocket(self,token,*message):
        m1,m2,m3 = message
        uri = "wss://push.611.com:6119/{}".format(token)
        ws = websocket.create_connection(uri, timeout=50)
        ws.send(m1)
        ws.send(m2)
        ws.send(m3)
        while True:
            result = ws.recv()
            print(result)

    def run(self):
        status, token = self.get_cookie()
        if not status:
            print('====token is error')
            return
        m1,m2,m3 = self.get_message()
        self.connect_websocket(token,m1,m2,m3)



if __name__ == '__main__':
    LeYu().run()

----参考python3反爬虫原理与绕过实战

你可能感兴趣的:(反爬)