Python獲取B站粉絲數(shù)的示例代碼
要使用代碼,需要安裝Python 3.x,并且要安裝庫,在cmd輸入pip install requests json time復(fù)制代碼,修改最上方變量改成你自己的UID,保存為xxx.py,運(yùn)行就可以了
用于學(xué)習(xí)了解的核心代碼:
import requestsimport jsonbilibili_api = requests.get('http://api.bilibili.com/x/relation/stat?vmid=1') # 訪問網(wǎng)址,數(shù)據(jù)存到變量,1是用戶UIDextracting_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 requestsimport jsonimport time# 需要修改的變量uid = 9824766 # 用戶UIDsleep_second = 60 # 多少秒檢測一次# 預(yù)定義變量 (不能修改)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 = ’’ # 預(yù)定義轉(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)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. Python多線程操作之互斥鎖、遞歸鎖、信號量、事件實例詳解2. Python常用GUI框架原理解析匯總3. XML入門的常見問題(一)4. Django程序的優(yōu)化技巧5. Jsp中request的3個基礎(chǔ)實踐6. idea設(shè)置自動導(dǎo)入依賴的方法步驟7. jsp EL表達(dá)式詳解8. 怎樣才能用js生成xmldom對象,并且在firefox中也實現(xiàn)xml數(shù)據(jù)島?9. IntelliJ IDEA 統(tǒng)一設(shè)置編碼為utf-8編碼的實現(xiàn)10. django 鏈接多個數(shù)據(jù)庫 并使用原生sql實現(xiàn)
