|
| 1 | +# Python3.7 |
| 2 | +# encoding=utf-8 |
| 3 | +import requests,time,json,os |
| 4 | +import qrcode # 生成二维码 |
| 5 | +import cv2 as cv # 读取二维码图片 |
| 6 | +from concurrent.futures import ThreadPoolExecutor |
| 7 | + |
| 8 | +''' |
| 9 | + 需要安装第三方库: |
| 10 | + pip install qrcode==7.3 |
| 11 | + pip install opencv-python==4.5.3.56 |
| 12 | +''' |
| 13 | + |
| 14 | +headers = { |
| 15 | + 'referer':'https://passport.bilibili.com/login', |
| 16 | + 'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36x-requested-with: XMLHttpRequest' |
| 17 | +} |
| 18 | + |
| 19 | +class Login(): |
| 20 | + |
| 21 | + def __init__(self): |
| 22 | + self.oauthKey = '' |
| 23 | + self.qrcodeURL = '' |
| 24 | + self.session = requests.Session() |
| 25 | + self.session.headers = headers |
| 26 | + |
| 27 | + # 获取二维码图片地址 |
| 28 | + def getQRcode(self): |
| 29 | + |
| 30 | + html = self.session.get('https://passport.bilibili.com/qrcode/getLoginUrl') |
| 31 | + if html.json()['status'] == True: |
| 32 | + self.oauthKey = html.json()['data']['oauthKey'] |
| 33 | + self.qrcodeURL = html.json()['data']['url'] |
| 34 | + return True |
| 35 | + return False |
| 36 | + |
| 37 | + # 利用 opencv 读取图片 |
| 38 | + @staticmethod |
| 39 | + def showQRCode(url): |
| 40 | + qrCode = qrcode.QRCode() |
| 41 | + qrCode.add_data(url) |
| 42 | + qrCode = qrCode.make_image() |
| 43 | + qrCode.save('qrCode.png') |
| 44 | + img = cv.imread('qrCode.png',1) |
| 45 | + cv.imshow('Login',img) |
| 46 | + cv.waitKey() |
| 47 | + |
| 48 | + # 开始登录 |
| 49 | + def login(self): |
| 50 | + |
| 51 | + # 创建另一个线程,展示二维码图片 |
| 52 | + thread_pool = ThreadPoolExecutor(max_workers=2) |
| 53 | + if self.getQRcode(): |
| 54 | + thread_pool.submit(self.showQRCode,self.qrcodeURL) |
| 55 | + |
| 56 | + # 不断检查二维码是否确认登录 |
| 57 | + while True: |
| 58 | + time.sleep(1) |
| 59 | + data = { |
| 60 | + 'oauthKey':self.oauthKey, |
| 61 | + 'gourl':'https://www.bilibili.com/' |
| 62 | + } |
| 63 | + |
| 64 | + html = self.session.post('https://passport.bilibili.com/qrcode/getLoginInfo',headers=headers,data=data) |
| 65 | + |
| 66 | + if html.json()['data'] == -4: # 还没扫码 |
| 67 | + pass |
| 68 | + elif html.json()['data'] == -2: # 二维码过期,需要重新生成 |
| 69 | + self.getQRcode() |
| 70 | + thread_pool.submit(self.showQRCode,self.qrcodeURL) |
| 71 | + elif html.json()['data'] == -5: # 已经扫码,等待确认 |
| 72 | + pass |
| 73 | + else: |
| 74 | + break |
| 75 | + |
| 76 | + # 解析 cookie |
| 77 | + cookieRaw = html.json()['data']['url'].split('?')[1].split('&') |
| 78 | + cookies = {} |
| 79 | + for cookie in cookieRaw: |
| 80 | + key,value = cookie.split('=') |
| 81 | + if key != 'gourl' and key != 'Expires': |
| 82 | + cookies[key] = value |
| 83 | + print(json.dumps(cookies)) |
| 84 | + os._exit(0) |
| 85 | + |
| 86 | +if __name__ == '__main__': |
| 87 | + login = Login() |
| 88 | + login.login() |
0 commit comments