NiceLeeのBlog 用爱发电 bilibili~

Python 批量删除B站动态

2021-03-07
nIceLee

阅读:


前阵子过年的时候参加新春厨神大作战,发了上百来条动态。
现在看着挺碍眼的,决定批量删除。

代码

如下,改下cookie即可

import requests,json,re


def get_dynamics(uid:str, cookie:str, offset_dynamic_id:int = 0):
    result = _http_get_dynamics(uid, cookie, offset_dynamic_id)
    while result["data"]["has_more"] == 1:
        for card in result["data"]["cards"]:
            # 请注意,返回的json里面有很多id、rid、dynamic_id、dynamic_id_str之类的,请取用dynamic_id_str
            yield card["desc"]["dynamic_id_str"], json.loads(card["card"])
        offset_dynamic_id = result["data"]["next_offset"]
        result = _http_get_dynamics(uid, cookie, offset_dynamic_id)

def _http_get_dynamics(uid, cookie, offset_dynamic_id = 0):
    headers = {
        "Accept": "application/json, text/plain, */*",
        "User-Agent": user_agent,
        "Accept-Encoding": "gzip, deflate",
        "Cookie": cookie,
    }
    url = "https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/space_history?visitor_uid=%s&host_uid=%s&offset_dynamic_id=%d&need_top=1&platform=web"%(uid, uid, offset_dynamic_id)
    res = requests.get(url, headers=headers).json()
    return res
    
def delete_dynamic(uid:str, dynamic_id_str:str, cookie):
    # {'code': 500406, 'msg': '不能删除别人的动态哦', 'message': '不能删除别人的动态哦', 'data': {}}
    # {'code': 500404, 'msg': '不能重复删除', 'message': '不能重复删除', 'data': {}}
    # {'code': 0, 'msg': '', 'message': '', 'data': {'_gt_': 0}}
    regexs = re.search("bili_jct=([^&; =]+)", cookie)
    if not regexs:
        raise Exception("cookie not valid")
        
    csrf_token = regexs.group(1)
    headers = {
        "Accept": "application/json, text/plain, */*",
        "User-Agent": user_agent,
        "Accept-Encoding": "gzip, deflate",
        "Content-Type": "application/x-www-form-urlencoded",
        "Origin": "https://space.bilibili.com",
        "Referer": "https://space.bilibili.com/%s/dynamic"%uid,
        "Cookie": cookie,
    }
    data = "dynamic_id=%s&csrf_token=%s&csrf=%s"%(dynamic_id_str, csrf_token, csrf_token)
    url = "https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/rm_dynamic"
    res = requests.post(url, data=data, headers=headers, verify=True).json()
    return res

def delete_dynamics(uid:str, cookie:str, isValid):
    for dynamic_id_str, card in get_dynamics(uid = uid, cookie = cookie, offset_dynamic_id = 0):
        if not isValid(card):
            res = delete_dynamic(uid=uid, dynamic_id_str=dynamic_id_str, cookie=cookie)
            if res["code"] == 0:
                print("%s 删除成功"%(dynamic_id_str))
            else:
                print("%s 删除失败"%(dynamic_id_str))


def check_valid_func(keyword:str, type: int = 0):

    # 不考虑转发内容,只考虑自己发的内容
    def is_dynamic_valid(dynamic:dict):
        if "desc" in dynamic:
            content = dynamic["desc"]
        elif "item" in dynamic and "content" in dynamic["item"]:
            content = dynamic["item"]["content"]
        elif "vest" in dynamic and "content" in dynamic["vest"]:
            content = dynamic["vest"]["content"]
        
        if keyword in content:
            return False
        else:
            return True
    
    # 考虑转发的内容和自己的内容
    def is_dynamic_valid_forward(dynamic:dict):
        if "origin" in dynamic:
            origin = json.loads(dynamic["origin"])
            item = origin["item"] if "item" in origin else origin
            if "description" in item and keyword in item["description"]:
                return False
            if "intro" in item and keyword in item["intro"]:
                return False
            if "title" in item and keyword in item["title"]:
                return False
        if "sketch" in dynamic:
            if keyword in dynamic["sketch"]["title"] or keyword in dynamic["sketch"]["desc_text"]:
                return False
        if "item" in dynamic and "content" in dynamic["item"]:
            if keyword in dynamic["item"]["content"]:
                return False
        return True
    
    if type == 0:
        return is_dynamic_valid
    else:
        return is_dynamic_valid_forward
user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:82.0) Gecko/20100101 Firefox/82.0"

if __name__ == "__main__":
    cookie = "xxx"
    uid = re.search("DedeUserID=([^&; =]+)", cookie).group(1)
    
    """
    罗列所有动态
    
    for dynamic_id_str, card in get_dynamics(uid = uid, cookie = cookie, offset_dynamic_id = 0):
        print(dynamic_id_str)
        print(card)
    """
    
    """
    调试删除动态(传入一个返回True的函数即可,可以将动态内容打印出来)
    B站返回的API真的是五花八门
    """
    def isValid(dynamic: dict):
        print(dynamic)
        return True
    result = delete_dynamics(uid, isValid = isValid, cookie = cookie) 
    
    
    """
    删除包含keyword的动态
    
    result = delete_dynamics(uid, cookie = cookie,\
        isValid = check_valid_func("新春厨神大作战", 1))
    print(result)
    """


内容
隐藏