python | websockets库的使用

python | websockets库的使用

最近又想玩玩b站的弹幕,就看了一下websockets库

pip install websockets

这个库是基于asyncio的,所以得用python3.7以上,然后用异步的方式去写,大概写了点demo:
有时间完善一下好了,这个方便的地方就是可以直接连接wss,很爽,不用自己配ssl啥的,中文的东西不多,更多看看官方文档就好。

import asyncio
import websockets
import aiohttp
import json
import struct
import re
import ssl

headers = {
	'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36',
	'Origin': 'https://live.bilibili.com',
	'Connection': 'Upgrade',
	'Accept-Language': 'zh-CN,zh;q=0.9',
}

class Pybilidanmu():
	def __init__(self):
		self.get_danmu_info_url = 'http://api.live.bilibili.com/xlive/web-room/v1/index/getDanmuInfo?id='
		self.roomid = "23952162"
		self.wss_url = 'wss://tx-bj-live-comet-01.chat.bilibili.com/sub'
		self.token = ""
		
		# ws连接
		self.ws_connect = None

	# get请求进入房间
	async def enter_room(self):
		url = self.get_danmu_info_url + self.roomid
		print(f'> 正在进入{url} ...')
		async with aiohttp.ClientSession() as s:
			async with s.get(url) as r:
				t = await r.text()
				data = json.loads(t)
				# print(json.dumps(data, indent=4))
				if data['code'] == 0:
					print('  > 进入房间成功')
					self.token = data['data']['token']
					host_list = data['data']['host_list']
					host = "wss://" + host_list[0]['host']
					port = host_list[0]['wss_port']
					self.wss_url = host+":"+str(port)+'/sub'   # 这里要加上sub不然连不上,笑死
					print(f'  > 弹幕地址: {self.wss_url}')
					# 连接弹幕服务器
					await self.connect_dm()
					
	# 心跳包
	async def heartbeat(self):
		pass
					
	# 连接wss
	async def connect_dm(self):
		print('> 正在连接wss服务器...')
		async with websockets.connect(
				self.wss_url, 
				extra_headers=headers
				) as websocket:
			# 发送登录包等等
			# ...
			while True:
				tmp = await websocket.recv()
				print(tmp)
		
		
		
		print('> 连接成功')
		




if __name__ == '__main__':
	client = Pybilidanmu()
	tasks = [
		client.enter_room(),
	]
	loop = asyncio.get_event_loop()
	try:
		loop.run_until_complete(asyncio.wait(tasks))
	except KeyboardInterrupt:
		for tasks in asyncio.Task.all_tasks():
			task.cancel()
		loop.run_forever()
	
	loop.close()


posted @ 2022-07-12 23:56  Mz1  阅读(4188)  评论(0编辑  收藏  举报