import requests
import json
bilibili_api = requests.get("http://api.bilibili.com/x/relation/stat?vmid=1") # 訪問網(wǎng)址,數(shù)據(jù)存到變量,1是用戶UID
extracting_json = bilibili_api.text # 提取bilibili_api的text數(shù)據(jù)
python_dictionary = json.loads(extracting_json) # json對象轉(zhuǎn)換為python字典
print(python_dictionary['data']['follower']) # 訪問python對象,data里的follower
import requests
import json
import time
# 需要修改的變量
uid = 9824766 # 用戶UID
sleep_second = 60 # 多少秒檢測一次
# 預定義變量 (不能修改)
assigned_value = 0 # 舊粉絲數(shù)變量是否賦值
fans_num_old = 0 # 上一次的粉絲數(shù)
while True:
# 嘗試訪問鏈接,如果OSError輸出連接失敗,并break。
try:
bilibili_api = requests.get("http://api.bilibili.com/x/relation/stat?vmid={}".format(uid)) # 訪問網(wǎng)址,數(shù)據(jù)存到變量
except OSError:
print('連接失敗')
break
extracting_json = bilibili_api.text # 提取bilibili_api的text數(shù)據(jù)
python_dictionary = json.loads(extracting_json) # json對象轉(zhuǎn)換為python字典
# 如果發(fā)送請求過多,被系統(tǒng)禁止獲取數(shù)據(jù),則提示并退出程序
try:
fans_num = python_dictionary['data']['follower'] # 粉絲數(shù),訪問python對象,data里的follower
except TypeError:
print('請求被攔截,需要更換IP訪問')
break
# 判斷舊粉絲數(shù)變量,是否被首次賦值
if assigned_value != 1:
fans_num_old = fans_num
assigned_value = 1
# 判斷粉絲數(shù)是否變化
if fans_num_old != fans_num:
num_change = fans_num - fans_num_old
num_charge_to_str = '' # 預定義轉(zhuǎn)換完的”改變多少粉絲數(shù)“變量
if num_change > 0: # 變化大于0就轉(zhuǎn)字符串,再添加+號
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站粉絲數(shù):', fans_num, '(', num_charge_to_str,
')',
sep='')
fans_num_old = fans_num # 存儲新粉絲數(shù)
time.sleep(sleep_second) # 每次循環(huán)檢測等待秒數(shù)
到此這篇關(guān)于Python獲取B站粉絲數(shù)的示例代碼的文章就介紹到這了,更多相關(guān)Python獲取B站粉絲數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!