最近 B 站出了一個年度報告,統計用戶一年當中在 B 站上觀看視頻的總時長和總個數。過去一年我竟然在 B 站上看了2600+
個視頻,總計251
個小時,竟然花了這麼多時間,嚇得我差點把 Bilibili App 卸載了...python
然而我又很好奇,到底我在 B 站上都看了些什麼類型小姐姐的視頻,用幾行 Python 代碼實現了一下。chrome
實現起來很是容易,獲取 cookie 模擬請求便可json
檢查
Network
頁面,篩選框輸入history
,對結果進行篩選,頁面滾輪往下便可看到瀏覽過程當中的歷史記錄請求的Header
cookie.txt
文本里
import json import requests def read_cookies_file(filename): """read cookie txt file :param filename: (str) cookies file path :return: (dict) cookies """ with open(filename, 'r') as fp: cookies = fp.read() return cookies def get_header(filename): cookie = read_cookies_file(filename) headers = { 'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7', 'Connection': 'keep-alive', 'Cookie': cookie, 'Host': 'api.bilibili.com', 'Referer': 'https://www.bilibili.com/account/history', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 ' '(KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36' } return headers def req_get(headers, url): resp = requests.get(url, headers=headers) return json.loads(resp.text)
def get_all_bili_history(cookie_file): headers = bilibili.get_header(cookie_file) history = {'all': []} for page_num in range(MAX_PAGE): time.sleep(0.6) url = 'https://api.bilibili.com/x/v2/history?pn={pn}&ps={ps}&jsonp=jsonp'.format(pn=page_num, ps=PAGE_PER_NUM) result = bilibili.req_get(headers, url) print('page = {} code = {} datalen = {}'.format(page_num, result['code'], len(result['data']))) if len(result['data']) == 0: break history['all'].append(result) return history
1000
條或者最近3
個月的播放記錄儘可能不要使用不安全的 wifi 網絡,有可能會被別有用心之人獲取網絡請求的 Package,易泄露我的隱私。api