1
+ import hashlib
2
+ import subprocess
3
+ import time
4
+ import json
5
+ import qrcode
6
+ from urllib .parse import urlencode
7
+
8
+ APP_KEY = "4409e2ce8ffd12b8"
9
+ APP_SEC = "59b43e04ad6965f34319062b478f83dd"
10
+
11
+ def signature (params ):
12
+ params ['appkey' ] = APP_KEY
13
+ keys = sorted (params .keys ())
14
+ query = '&' .join (f"{ k } ={ params [k ]} " for k in keys )
15
+ query += APP_SEC
16
+ md5_hash = hashlib .md5 (query .encode ('utf-8' )).hexdigest ()
17
+ params ['sign' ] = md5_hash
18
+
19
+ def map_to_string (params ):
20
+ return urlencode (params )
21
+
22
+ def execute_curl_command (api , data ):
23
+ data_string = map_to_string (data )
24
+ headers = "Content-Type: application/x-www-form-urlencoded"
25
+ curl_command = f"curl -X POST -H \" { headers } \" -d \" { data_string } \" { api } "
26
+ result = subprocess .run (curl_command , shell = True , capture_output = True , text = True )
27
+ if result .returncode != 0 :
28
+ raise Exception (f"curl command failed: { result .stderr } " )
29
+ return json .loads (result .stdout )
30
+
31
+ def get_tv_qrcode_url_and_auth_code ():
32
+ api = "https://passport.bilibili.com/x/passport-tv-login/qrcode/auth_code"
33
+ data = {
34
+ "local_id" : "0" ,
35
+ "ts" : str (int (time .time ()))
36
+ }
37
+ signature (data )
38
+ body = execute_curl_command (api , data )
39
+ if body ['code' ] == 0 :
40
+ qrcode_url = body ['data' ]['url' ]
41
+ auth_code = body ['data' ]['auth_code' ]
42
+ return qrcode_url , auth_code
43
+ else :
44
+ raise Exception ("get_tv_qrcode_url_and_auth_code error" )
45
+
46
+ def verify_login (auth_code ):
47
+ api = "https://passport.bilibili.com/x/passport-tv-login/qrcode/poll"
48
+ data = {
49
+ "auth_code" : auth_code ,
50
+ "local_id" : "0" ,
51
+ "ts" : str (int (time .time ()))
52
+ }
53
+ signature (data )
54
+ while True :
55
+ body = execute_curl_command (api , data )
56
+ if body ['code' ] == 0 :
57
+ print ("Login success!" )
58
+ filename = "cookie.json"
59
+ with open (filename , 'w' , encoding = 'utf-8' ) as f :
60
+ json .dump (body , f , ensure_ascii = False , indent = 4 )
61
+ print (f"cookie has been saved to { filename } " )
62
+ break
63
+ else :
64
+ time .sleep (3 )
65
+
66
+ def login_bili ():
67
+ input ("Please maximize the window to ensure the QR code is fully displayed, press Enter to continue: " )
68
+ login_url , auth_code = get_tv_qrcode_url_and_auth_code ()
69
+ qr = qrcode .QRCode ()
70
+ qr .add_data (login_url )
71
+ qr .print_ascii ()
72
+ print ("Or copy this link to your phone Bilibili:" , login_url )
73
+ verify_login (auth_code )
74
+
75
+ if __name__ == "__main__" :
76
+ login_bili ()
0 commit comments