forked from wbt5/real-url
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bilibili.py
86 lines (76 loc) · 3 KB
/
bilibili.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# 获取哔哩哔哩直播的真实流媒体地址,默认获取直播间提供的最高画质
# qn=150高清
# qn=250超清
# qn=400蓝光
# qn=10000原画
import requests
class BiliBili:
def __init__(self, rid):
"""
有些地址无法在PotPlayer播放,建议换个播放器试试
Args:
rid:
"""
rid = rid
self.header = {
'User-Agent': 'Mozilla/5.0 (iPod; CPU iPhone OS 14_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, '
'like Gecko) CriOS/87.0.4280.163 Mobile/15E148 Safari/604.1',
}
# 先获取直播状态和真实房间号
r_url = 'https://api.live.bilibili.com/room/v1/Room/room_init'
param = {
'id': rid
}
with requests.Session() as self.s:
res = self.s.get(r_url, headers=self.header, params=param).json()
if res['msg'] == '直播间不存在':
raise Exception(f'bilibili {rid} {res["msg"]}')
live_status = res['data']['live_status']
if live_status != 1:
raise Exception(f'bilibili {rid} 未开播')
self.real_room_id = res['data']['room_id']
def get_real_url(self, current_qn: int = 10000) -> dict:
url = 'https://api.live.bilibili.com/xlive/web-room/v2/index/getRoomPlayInfo'
param = {
'room_id': self.real_room_id,
'protocol': '0,1',
'format': '0,1,2',
'codec': '0,1',
'qn': current_qn,
'platform': 'h5',
'ptype': 8,
}
res = self.s.get(url, headers=self.header, params=param).json()
stream_info = res['data']['playurl_info']['playurl']['stream']
qn_max = 0
for data in stream_info:
accept_qn = data['format'][0]['codec'][0]['accept_qn']
for qn in accept_qn:
qn_max = qn if qn > qn_max else qn_max
if qn_max != current_qn:
param['qn'] = qn_max
res = self.s.get(url, headers=self.header, params=param).json()
stream_info = res['data']['playurl_info']['playurl']['stream']
stream_urls = {}
# flv流无法播放,暂修改成获取hls格式的流,
for data in stream_info:
format_name = data['format'][0]['format_name']
if format_name == 'ts':
base_url = data['format'][-1]['codec'][0]['base_url']
url_info = data['format'][-1]['codec'][0]['url_info']
for i, info in enumerate(url_info):
host = info['host']
extra = info['extra']
stream_urls[f'线路{i + 1}'] = f'{host}{base_url}{extra}'
break
return stream_urls
def get_real_url(rid):
try:
bilibili = BiliBili(rid)
return bilibili.get_real_url()
except Exception as e:
print('Exception:', e)
return False
if __name__ == '__main__':
r = input('请输入bilibili直播房间号:\n')
print(get_real_url(r))