Last active 1726944581

bilibili.py Raw
1#!/usr/bin/env python3
2# -*- encoding: utf-8 -*-
3# Author: AimerNeige
4# Site: https://aimerneige.com
5# Mail: aimer.neige.soft@gmail.com
6
7import requests
8import subprocess
9import json
10import sys
11
12
13def get_json(mid:'int', ps:'int', pn:'int') -> 'str':
14 """
15 Get json data from bilibili api
16 :param mid: user id
17 :param ps: item number per page
18 :param pn: current page
19 :return str: json data
20 """
21
22 url = "http://api.bilibili.com/x/space/arc/search?mid=%d&ps=%d&pn=%d" % (mid, ps, pn)
23 response = requests.get(url)
24 assert response.status_code == 200, "Request failed!"
25 response.encoding = 'utf-8'
26 json_data = response.text
27 return json_data
28
29
30def get_bv_id(json_data:'str') -> 'list':
31 """
32 Get all BV id from json data
33 "param json_data: json data
34 :return list: list of bvid
35 """
36 bv_id_list = []
37 obj = json.loads(json_data)
38 video_list = obj['data']['list']['vlist']
39 for video in video_list:
40 bv_id_list.append(video["bvid"])
41 return bv_id_list
42
43
44def download_video(url:'str'):
45 """
46 Call an subprogress and download video with `you-get`
47 :param url: Video url of bilibili
48 :return: None
49 """
50 print("Start Download %s" % (url))
51 subprocess.call("you-get %s" % (url), shell=True)
52 # print("Download %s" % (url))
53
54
55def print_help():
56 # Just simply print help menu
57 help_str = """
58Run this with a bilibii user space url, like this:
59 `python3 main.py https://space.bilibili.com/13081489`
60Or you can just give the uid, like this:
61 `python3 main.py 13081489`"""
62 print(help_str)
63
64
65def main():
66 # Main function
67 sys_argv = sys.argv
68 sys_argc = len(sys_argv)
69 mid = 13081489
70 pn = 1
71 ps = 100
72 if sys_argc == 1:
73 print("Please give more argument!")
74 print_help()
75 exit()
76 elif sys_argc == 2:
77 try:
78 int(sys_argv[1])
79 except:
80 try:
81 int(sys_argv[1].split('/')[3])
82 except:
83 print("Wrong Argument, please check your url.")
84 print_help()
85 exit()
86 else:
87 mid = int(sys_argv[1].split('/')[3])
88 else:
89 mid = int(sys_argv[1])
90 finally:
91 count = int(json.loads(get_json(mid, ps, pn))['data']['page']['count'])
92 pages = int(count / ps + 1)
93 for i in range(1, pages + 1):
94 json_data = get_json(mid, ps, i)
95 bv_id_list = get_bv_id(json_data)
96 for bv_id in bv_id_list:
97 download_video("https://www.bilibili.com/video/%s" % (bv_id))
98 else:
99 print("Wrong Argument!")
100 print_help()
101 exit()
102
103
104if __name__ == "__main__":
105 main()