python 获取cookie_用Python获取B站播放历史记录 !男友居然天天背着我看这些!

今天Geek专栏为大家带来

乐聚机器人王松博士的

“用Python获取B站播放历史记录”

65f31531e05644ec4657cb377e3838b5.png

最近 B 站出了一个年度报告,统计用户一年当中在 B 站上观看视频的总时长和总个数。过去一年我居然在 B 站上看了 2600+ 个视频,总计 251 个小时,居然花了这么多时间,吓得我差点把 Bilibili App 卸载了...

44e7458810fb5243c8ea25fc720934f5.png

然而我又很好奇,到底我在 B 站上都看了些什么类型 小姐姐 的视频,用几行 Python 代码实现了一下。

获取请求 Api 接口与 Cookie

实现起来非常容易,获取 cookie 模拟请求即可

1. 使用 chrome 浏览器

2. 登陆 B 站,进入历史记录 https://www.bilibili.com/account/history

3. 在网页任意位置,鼠标右键 检查

ba4cb23e4761e55fafd91127b80d7047.png

4. 按照下图所示,进入 Network 页面,筛选框输入 history,对结果进行筛选,页面滚轮往下即可看到浏览过程中的历史记录请求的 Header

67e85c2bfbf3e70a1ebee0719b8fbbbd.png

5. 将 Header 下, cookie 一行的字符串复制出来到一个 cookie.txt 文本里

a84cb79d79529d3dd34cd6afd5f80712.png

Python 代码实现

伪造浏览器请求

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)

使用 cookie 模拟请求

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

代码非常简单,完整代码在 https://github.com/wangshub/bilibili-history

存在的问题

本来想拿到所有的播放记录,做一些统计和预测,但是经过实测,B 站只能获取到最近 1000 条或者最近 3 个月的播放记录

如果想获得更多,只能做一个监测程序,不停地从接口获取数据

安全问题

尽量不要使用不安全的 wifi 网络,有可能会被别有用心之人获取网络请求的 Package,易泄露个人隐私。

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值