python3----练习题(弹幕跟随)

 1 # 导入模块
 2 import requests  # 1. 网络请求  2.pip install requests
 3 import time  # 用于时间控制
 4 import random  # 随机模块 产生随机数
 5 
 6 class SendLiveRoll():
 7 
 8     # 会自己先一步其他函数执行, 初始化函数
 9     def __init__(self, roomid):  # roomid 直播的房间号 7038113
10 
11         # 初始化直播的房间号
12         self.roomid = roomid
13 
14         # 获取弹幕的真实网址
15         self.url_1 = 'https://api.live.bilibili.com/ajax/msg'
16         self.form1 = {'roomid': self.roomid,
17                       'token': ' ',
18                       'csrf_token': '40242274df1884f06127398e447c4ab1'
19                       }
20         # 获取发送弹幕幕的真实网址
21         self.url_2 = 'https://api.live.bilibili.com/msg/send'
22         # 获取cookie
23         self.cookie = {'Cookie':''} # 你的Cookies
24     # 获取弹幕的函数
25     def getDanMu(self):
26 
27         # 获取弹幕
28         html_1 = requests.post(self.url_1, data=self.form1)
29 
30         # 提取弹幕
31         self.danmu = html_1.json()['data']['room'][random.randint(0, 3)]['text']
32         print(self.danmu)
33 
34         # 发送弹幕的函数
35     def sendDanMu(self):
36         t = time.time()
37         self.form2 = {'color': '16777215',
38                       'fontsize': '25',
39                       'mode': '1',
40                       'msg': self.danmu,
41                       'rnd': int(t),
42                       'roomid': self.roomid}
43         requests.post(self.url_2, data=self.form2, cookies=self.cookie)
44 
45 
46 
47 
48 if __name__ == '__main__':
49 
50     while True:
51         time.sleep(random.randint(2, 6))
52         danmu = SendLiveRoll(1105379)
53         danmu.getDanMu()
54         danmu.sendtDanMu()
原文地址:https://www.cnblogs.com/jonm/p/8310703.html