Sample code for Python to get the number of fans in B station

  • 2021-10-15 10:55:57
  • OfStack

To use the code, you need to install Python 3. x, and to install the library, enter pip install requests json time at cmd
Copy the code, change the top variable to your own UID, save it as xxx. py, and run it

Core code for learning to understand:


import requests
import json

bilibili_api = requests.get("http://api.bilibili.com/x/relation/stat?vmid=1") #  Visit the URL, save the data to the variables, 1 Is a user UID
extracting_json = bilibili_api.text #  Extraction bilibili_api Adj. text Data 
python_dictionary = json.loads(extracting_json) # json Object to the python Dictionary 
print(python_dictionary['data']['follower']) #  Visit python Object, data In follower

Main article:


import requests
import json
import time

#  Variables to be modified 
uid = 9824766 #  Users UID
sleep_second = 60 #  How many seconds to detect 1 Times 
#  Predefined variable   (Cannot be modified) 
assigned_value = 0 #  Whether the number of old fans variable is assigned 
fans_num_old = 0 #  Upper 1 Number of fans per time 
while True:
  #  Try to access the link if OSError Output connection failed, and break . 
  try:
    bilibili_api = requests.get("http://api.bilibili.com/x/relation/stat?vmid={}".format(uid)) #  Visit the website address and save the data to the variable 
  except OSError:
    print(' Connection failed ')
    break
  extracting_json = bilibili_api.text #  Extraction bilibili_api Adj. text Data 
  python_dictionary = json.loads(extracting_json) # json Object to the python Dictionary 
  #  If you send too many requests and are forbidden by the system to obtain data, prompt and exit the program 
  try:
    fans_num = python_dictionary['data']['follower'] #  Number of fans, visits python Object, data In follower
  except TypeError:
    print(' Request intercepted and needs to be replaced IP Visit ')
    break
  #  Determine whether the old fan number variable is assigned for the first time 
  if assigned_value != 1:
    fans_num_old = fans_num
    assigned_value = 1
  #  Judge whether the number of fans changes 
  if fans_num_old != fans_num:
    num_change = fans_num - fans_num_old
    num_charge_to_str = '' #  Predefined "How many fans to change" variable after conversion 
    if num_change > 0: #  Change greater than 0 Just turn the string and add it + No. 
      num_charge_to_str = '+' + str(num_change)
    else:
      num_charge_to_str = str(num_change)
    print('[', time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), '] B Number of fans at the station: ', fans_num, '(', num_charge_to_str,
       ')',
       sep='')
    fans_num_old = fans_num #  Store the number of new fans 
  time.sleep(sleep_second) #  Number of seconds waiting for detection per loop 

Related articles: