Python模擬登陸 —— 征服驗(yàn)證碼 2 B站

B站的登錄密碼用了rsa加密(兩個(gè)大質(zhì)數(shù)的乘積很難進(jìn)行逆向分解,所以可以用這個(gè)乘積來做公鑰)。
所以運(yùn)行py文件之前,使用鏡像,先用pip安裝rsa庫:

pip install rsa -i https://pypi.tuna.tsinghua.edu.cn/simple/

運(yùn)行:

import requests
import re
import time
import sys
import json  
import rsa
import os.path
import binascii
import datetime
from bs4 import BeautifulSoup
try:
    import cookielib
except:
    import http.cookiejar as cookielib

try:
    from PIL import Image
except:
    pass
    
session = requests.Session()
session.headers = {
    'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:50.0) Gecko/20100101 Firefox/50.0',
    'Connection': 'keep-alive',
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
}

# 使用登錄cookie信息
session = requests.session()
session.cookies = cookielib.LWPCookieJar(filename='cookies')
try:
    session.cookies.load(ignore_discard=True)
except:
    print("Cookie 未能加載")

def rsaEncrypt(password):
    url = 'http://passport.bilibili.com/login?act=getkey'
    try:
        getKeyRes = session.get(url)
        token = json.loads(getKeyRes.content.decode('utf-8'))
        pw = str(token['hash'] + password).encode('utf-8')

        key = token['key']
        key = rsa.PublicKey.load_pkcs1_openssl_pem(key)

        pw = rsa.encrypt(pw, key)
        password = binascii.b2a_base64(pw)
        return password
    except:
        return False

def get_vdcode():
    t = str(int(time.time()*1000))
    captcha_url = 'https://passport.bilibili.com/captcha.gif?r=' + t + "&type=login"
    r = session.get(captcha_url)
    with open('captcha.jpg', 'wb') as f:
        f.write(r.content)
        f.close()
    # 用pillow 的 Image 顯示驗(yàn)證碼
    # 如果沒有安裝 pillow 到源代碼所在的目錄去找到驗(yàn)證碼然后手動輸入
    try:
        im = Image.open('captcha.jpg')
        im.show()
        im.close()
    except:
        print(u'請到 %s 目錄找到captcha.jpg 手動輸入' % os.path.abspath('captcha.jpg'))
    captcha = input("please input the captcha\n>")
    return captcha
    
def login(user, password):
    post_url = 'https://passport.bilibili.com/login/dologin'
    payload = {
        'act': 'login',
        'gourl': '',
        'keeptime': '2592000',
        'userid': user,
        'pwd': password,
        'vdcode': get_vdcode(),
    }
    if payload["vdcode"] == None:
        return False

    try:
        resp = session.post(post_url, data=payload)
        session.cookies.save()

        soup = BeautifulSoup(resp.content, 'lxml')
        s = str(soup.select('center')[0])
        s = s.replace('\n', '')
        s = s.replace('\r', '')
        s = s.replace(' ', '')
        s = s.split('>')
        s = s[2]
        s = s.replace('<br/', '')
        flash(s)
        return False
    except requests.exceptions.ConnectionError as e:
        flash(e)
        return False
    except:
        return True

def isLogin():
    url = 'https://account.bilibili.com/home/userInfo'
    resp = session.get(url, allow_redirects=False)
    if  resp.status_code == 200 and resp.json()['code'] == 0:
        return True
    else:
        return False

if __name__ == '__main__':
    if isLogin():
        print('您已經(jīng)登錄')
    else:
        account = input('請輸入你的用戶名:')
        password = input('請輸入密碼:')
        login(account, rsaEncrypt(password))

滑塊驗(yàn)證見http://www.itdecent.cn/p/7623ff64ee54

登錄界面

一張有趣的合照
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容