275天 倾丞

心随我意 路行千里

92行代码使用二维码获取哔哩哔哩登录cookies

倾丞 / 1个月前 / 99 次围观 / 3 条评论 / 技术分析 / [百度已收录] / 返回

各位想要爬取B站的小伙伴最头疼的应该就是怎么登录了,一位MRArchive的b站up主就来展示了一下怎么用python实现使用二维码登录哔哩哔哩。

详细的视频讲解可以回复本文章页后查看。

代码如下:

import json
import os
import qrcode
import requests
from concurrent.futures import ThreadPoolExecutor
import time
import cv2 as cv


class Login:
    def __init__(self):
        self.oauthKey = ''
        self.qrcodeUrl = ''
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0',
            'Accept': 'application/json, text/plain, */*',
            'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
            'Accept-Encoding': 'gzip, deflate, br',
            'Referer': 'https://passport.bilibili.com/',
            'Origin': 'https://passport.bilibili.com',
            'Connection': 'keep-alive'
        }
        self.session = requests.Session()
        self.session.headers.update(
            {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0'})

    def _requests(self, method, url, decode_level=2, retry=10, timeout=15, **kwargs):
        if method in ["get", "post"]:
            for _ in range(retry + 1):
                try:
                    response = getattr(self.session, method)(url, timeout=timeout, **kwargs)
                    return response.json() if decode_level == 2 else response.content if decode_level == 1 else response
                except:
                    pass
        return None

    def getQRCode(self):
        req = self._requests('get', "https://passport.bilibili.com/qrcode/getLoginUrl")
        if req and req.get('code') == 0:
            self.oauthKey = req['data']['oauthKey']
            self.qrcodeUrl = req['data']['url']
            return True
        return False

    @staticmethod
    def showQRCode(url):
        try:
            cv.destroyAllWindows()
        except:
            pass
        qrCode = qrcode.QRCode()
        qrCode.add_data(url)
        qrCode = qrCode.make_image()
        qrCode.save("qrCode.png")
        img = cv.imread("qrCode.png", 1)
        cv.imshow("Login", img)
        cv.waitKey()

    def login(self):
        pool = ThreadPoolExecutor(max_workers=2)
        if self.getQRCode():
            pool.submit(self.showQRCode, self.qrcodeUrl)
            while True:
                time.sleep(1)
                data = {
                    'oauthKey': self.oauthKey,
                    'gourl': "https://passport.bilibili.com/account/security"
                }
                req = self._requests('post', "https://passport.bilibili.com/qrcode/getLoginInfo", data=data)
                if req['data'] == -4:  # 未扫码
                    pass
                elif req['data'] == -2:  # 二维码过期,需要重新生成
                    self.getQRCode()
                    pool.submit(self.showQRCode, self.qrcodeUrl)
                elif req['data'] == -5:  # 已经扫码,等待确认
                    pass
                else:
                    break
            cookiesRaw = req['data']['url'].split('?')[1].split('&')
            cookies = {}
            for cookie in cookiesRaw:
                key, value = cookie.split('=')
                if key != "gourl" and key != "Expires":
                    cookies[key] = value
            print(json.dumps(cookies))
            os._exit(0)


if __name__ == '__main__':
    a = Login()
    a.login()

详细视频与已打包源码:

管理员设置回复可见隐藏内容

未显示?请点击刷新
  1. 1个月前 (06-26)
    @
    111

    支持

  2. 1个月前 (06-24)
    @
    abc

    支持支持zicizici

  3. 1个月前 (06-22)
    @
    KIS2

    支持