python 实现 短信登录 b站 并打印cookie内容

Posted Love丶伊卡洛斯

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 实现 短信登录 b站 并打印cookie内容相关的知识,希望对你有一定的参考价值。

前言

本程序是get_bili_medal_list项目
的一个子程序,用于大批量获取用户数据时的cookie替换。

使用

项目根目录运行python login_get_cookie.py,根据提示完成短信验证登录。
期间需要访问http://geetest.colter.top/,传入gtchallenge完成手动的极验校验,获取validateseccode
最后需要填入手机验证码完成登录即可。
ps:python login_get_cookie.py 1,优化了validateseccode的输入,请自行选择执行。



源码

login_get_cookie.py

依赖的第三方库,自行补装一下

import json
import asyncio
import aiohttp
import sys, re
from itertools import islice

header1 = 
    'content-type': 'application/x-www-form-urlencoded',
    "referer": "https://space.bilibili.com",
    "Origin": "https://space.bilibili.com",
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (Khtml, like Gecko) Chrome/94.0.4606.71 Safari/537.36 Core/1.94.186.400 '


proxys = None

# 国家id转对应的cid
async def get_cid(country_id):
    with open("data/country.json", "r", encoding="utf8") as f:
        country_data = json.load(f)
    
    for common in country_data["data"]["common"]:
        if common["country_id"] == country_id:
            return common["id"]
    
    return 1

# 获取验证码相关信息
async def get_check():
    API_URL = 'https://passport.bilibili.com/x/passport-login/captcha?source=main_web'
    async with aiohttp.ClientSession(headers=header1) as session:
        try:
            async with session.get(url=API_URL, headers=header1, proxy=proxys) as response:
                if response.status != 200:
                    response.raise_for_status()
                ret = await response.json()
        except aiohttp.ClientError as e:
            print(e)
            return "code": -1
            
    return ret


# 获取captcha_key喵
async def get_captcha_key(post_data):
    API_URL = 'https://passport.bilibili.com/x/passport-login/web/sms/send'
    async with aiohttp.ClientSession(headers=header1) as session:
        try:
            async with session.post(url=API_URL, headers=header1, proxy=proxys, data=post_data) as response:
                if response.status != 200:
                    response.raise_for_status()
                ret = await response.json()
        except aiohttp.ClientError as e:
            print(e)
            return "code": -400
            
    return ret


# 登录
async def login(post_data):
    API_URL = 'https://passport.bilibili.com/x/passport-login/web/login/sms'
    async with aiohttp.ClientSession(headers=header1) as session:
        try:
            async with session.post(url=API_URL, headers=header1, proxy=proxys, data=post_data) as response:
                if response.status != 200:
                    response.raise_for_status()

                print("\\n返回的cookie如下")
                print(response.cookies)
                
                ret = await response.json()
        except aiohttp.ClientError as e:
            print(e)
            return "code": -400
            
    return ret

async def main():
    banner = r"""
            \\\\         //
            \\\\       //
        #####################     ________   ___   ___        ___   ________   ___   ___        ___
        ##                 ##    |\\   __  \\ |\\  \\ |\\  \\      |\\  \\ |\\   __  \\ |\\  \\ |\\  \\      |\\  \\
        ##    //     \\\\    ##    \\ \\  \\|\\ /_\\ \\  \\\\ \\  \\     \\ \\  \\\\ \\  \\|\\ /_\\ \\  \\\\ \\  \\     \\ \\  \\
        ##   //       \\\\   ##     \\ \\   __  \\\\ \\  \\\\ \\  \\     \\ \\  \\\\ \\   __  \\\\ \\  \\\\ \\  \\     \\ \\  \\
        ##                 ##      \\ \\  \\|\\  \\\\ \\  \\\\ \\  \\____ \\ \\  \\\\ \\  \\|\\  \\\\ \\  \\\\ \\  \\____ \\ \\  \\
        ##       www       ##       \\ \\_______\\\\ \\__\\\\ \\_______\\\\ \\__\\\\ \\_______\\\\ \\__\\\\ \\_______\\\\ \\__\\
        ##                 ##        \\|_______| \\|__| \\|_______| \\|__| \\|_______| \\|__| \\|_______| \\|__|
        #####################
            \\/         \\/                               哔哩哔哩 (゜-゜)つロ 干杯~
    """

    # 获取captcha_key的传参
    post_data1 = 
        "cid": "86",
        "tel" : "0",
        "source" : "main-fe-header",
        "token" : "",
        "challenge" : "",
        "validate" : "",
        "seccode" : ""
    
    # 登录传参
    post_data2 = 
        "cid": "86",
        "tel" : "0",
        "code" : 0,
        "source" : "main-fe-header",
        "captcha_key" : ""
    

    print(banner + "\\n")

    # 获取命令行传入的参数
    args = sys.argv

    # 输出命令行传入的参数
    # print(args)

    country_id = input("请输入手机的国家代码(不填默认 86):")
    tel = input("请输入手机号码:")

    if country_id == "":
        # post_data1["cid"] = 1
        country_id = "86"

    # 获取下cid
    # post_data1["cid"] = await get_cid(country_id)
    post_data1["cid"] = country_id

    if tel == "":
        print("输入手机号啊!kora!")
        return
    else:
        post_data1["tel"] = tel

    print("[开始获取验证信息]")
    token_json = await get_check()
    print(json.dumps(token_json, indent=2, ensure_ascii=False))

    if token_json["code"] != 0:
        print("获取校验信息失败,取名为寄喵~")
        return

    try:
        post_data1["token"] = token_json["data"]["token"]
        gt = post_data1["challenge"] = token_json["data"]["geetest"]["gt"]
        post_data1["challenge"] = token_json["data"]["geetest"]["challenge"]

        print("\\n请访问:http://geetest.colter.top/ 继续验证码的校验,获取validate和seccode")
        print("gt=\\n" + gt)
        print("challenge=\\n" + post_data1["challenge"])
        print("\\n")

        # 传参 不传参则是普通模式;传入1个参数 任何内容,则定制优化模式
        if len(args) >= 2:
            validate_seccode = input("请输入快捷复制的validate&seccode:")
            match = re.search('validate=(.*)&seccode=(.*)', validate_seccode)
            validate = match.group(1)
            seccode = match.group(2)
        else:
            validate = input("请输入验证后的validate:")
            seccode = input("请输入验证后的seccode:")

        if validate == "" or seccode == "":
            print("空值是达咩的啦~如果验证失败,可以重新运行重试~")
            return

        post_data1["validate"] = validate
        post_data1["seccode"] = seccode

        print(json.dumps(post_data1, indent=2, ensure_ascii=False))
        print("[传参内容集齐啦!开冲!]\\n")
        
        captcha_key_json = await get_captcha_key(post_data1)

        try:
            if captcha_key_json["code"] != 0:
                print("失败了喵~,请求返回如下")
                print(json.dumps(captcha_key_json, indent=2, ensure_ascii=False))
                return

            print("短信验证码发送成功!")
            print(json.dumps(captcha_key_json, indent=2, ensure_ascii=False))

            print("\\n请在5分钟内完成验证哦~")
            code = input("请输入手机收到的验证码:")

            if code == "":
                print("空验证码???")
                return
            else:
                post_data2["code"] = code

            post_data2["cid"] = post_data1["cid"]
            post_data2["tel"] = post_data1["tel"]
            post_data2["captcha_key"] = captcha_key_json["data"]["captcha_key"]


            login_json = await login(post_data2)

            try:
                if login_json["code"] != 0:
                    print("\\n登录失败喵~请求返回如下")
                    print(json.dumps(login_json, indent=2, ensure_ascii=False))
                    return
                
                # print(json.dumps(login_json, indent=2, ensure_ascii=False))

                print("\\n登录成功!!!")

                if login_json["data"]["is_new"] == True:
                    print("新注册用户")
            except Exception as e:
                print(e)
                return

        except Exception as e:
            print(e)
            return


    except Exception as e:
        print(e)
        return

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

data/country.json

"code":0,"data":"common":["id":1,"cname":"中国大陆","country_id":"86","id":5,"cname":"中国香港特别行政区","country_id":"852","id":2,"cname":"中国澳门特别行政区","country_id":"853","id":3,"cname":"中国台湾","country_id":"886","id":4,"cname":"美国","country_id":"1","id":6,"cname":"比利时","country_id":"32","id":7,"cname":"澳大利亚","country_id":"61","id":8,"cname":"法国","country_id":"33","id":9,"cname":"加拿大","country_id":"1","id":10,"cname":"日本","country_id":"81","id":11,"cname":"新加坡","country_id":"65","id":12,"cname":"韩国","country_id":"82","id":13,"cname":"马来西亚","country_id":"60","id":14,"cname":"英国","country_id":"44","id":15,"cname":"意大利","country_id":"39","id":16,"cname":"德国","country_id":"49","id":18,"cname":"俄罗斯","country_id":"7","id":19,"cname":"新西兰","country_id":"64"],"others":["id":22,"cname":"阿富汗","country_id":"93","id":20,"cname":"阿尔巴尼亚","country_id":"355","id":21,"cname":"阿尔及利亚","country_id":"213","id":31,"cname":"安道尔","country_id":"376","id":32,"cname":"安哥拉","country_id":"244","id":33,"cname":"安提瓜岛和巴布达","country_id":"1268","id":23,"cname":"阿根廷","country_id":"54","id":204,"cname":"亚美尼亚","country_id":"374","id":183,"cname":"阿森松岛","country_id":"247","id":34,"cname":"奥地利","country_id":"43","id":26,"cname":"阿塞拜疆","country_id":"994","id":37,"cname":"巴哈马群岛","country_id":"1242","id":40,"cname":"巴林","country_id":"973","id":131,"cname":"孟加拉国","country_id":"880","id":35,"cname":"巴巴多斯","country_id":"1246","id":43,"cname":"白俄罗斯","country_id":"375","id":52,"cname":"伯利兹","country_id":"501","id":46,"cname":"贝宁","country_id":"229","id":44,"cname":"百慕大群岛","country_id":"1441","id":54,"cname":"不丹","country_id":"975","id":51,"cname":"玻利维亚","country_id":"591","id":49,"cname":"波黑","country_id":"387","id":53,"cname":"博茨瓦纳","country_id":"267","id":42,"cname":"巴西","country_id":"55","id":193,"cname":"文莱","country_id":"673","id":45,"cname":"保加利亚","country_id":"359","id":55,"cname":"布基纳法索","country_id":以上是关于python 实现 短信登录 b站 并打印cookie内容的主要内容,如果未能解决你的问题,请参考以下文章

原来Python爬虫还可以这么玩!python爬虫自动化实现B站自动登录

原来Python爬虫还可以这么玩!python爬虫自动化实现B站自动登录

短信验证登录实现流程

最新selenium+验证码识别模拟登陆B站

CSRF跨站请求伪造攻击

循环监测b站用户粉丝数舰长数及增量 程序