爬虫登陆实战 — QQ音乐扫码登陆

爬虫实战教程

    • 授人以鱼不如授人以渔
    • 开始实战
      • 准备工作
        • 编写代码
      • 抓取二维码下载链接
        • 编写代码
      • 登陆抓包准备
    • 棘手的可变加密参数
      • 第一个参数
        • 编写代码
      • 第二个参数 1.获取
        • 编写代码
      • 第二个参数hash33加密
    • 全部代码

授人以鱼不如授人以渔

爬虫教程千千万,总觉得市面的教程很少教到精髓。
这一期做一个本地扫码登陆获取Session的爬虫。

开始实战

准备工作

我们的目标是能够将QQ音乐的扫码登陆在本地执行。
也就是保存登陆二维码到本地,弹出二维码,若登陆成功后删除二维码,保留登陆信息。

我们首先写出显示二维码函数、删除二维码函数、保存二维码函数。

编写代码

import sys
import os 
import subprocess
'''用于在不同OS显示验证码'''
def showImage(img_path):
    try:
        if sys.platform.find('darwin') >= 0: subprocess.call(['open', img_path])
        elif sys.platform.find('linux') >= 0: subprocess.call(['xdg-open', img_path])
        else: os.startfile(img_path)
    except:
        from PIL import Image
        img = Image.open(img_path)
        img.show()
        img.close()

'''验证码验证完毕后关闭验证码并移除'''
def removeImage(img_path):
    if sys.platform.find('darwin') >= 0:
        os.system("osascript -e 'quit app \"Preview\"'")
    os.remove(img_path)

'''保存验证码图像'''
def saveImage(img, img_path):
    if os.path.isfile(img_path):
        os.remove(img_path)
    fp = open(img_path, 'wb')
    fp.write(img)
    fp.close()

抓取二维码下载链接

进入QQ空间后打开F12开发者工具,将登陆按钮点开弹出登陆框。

我们首先先获取我们的图片信息,点开Img选项里面往下拉,找到二维码的网页链接。

点开Headers查看获取该图片需要什么链接:

  • 首先是个GET请求(Request Method中查看)
  • 其次URL为https://ssl.ptlogin2.qq.com/ptqrshow(问号前的网址为根部URL,问号后为参数)

再看看该二维码网站需要的参数:

  • appid: 716027609
  • e: 2
  • l: M
  • s: 3
  • d: 72
  • v: 4
  • t: 0.07644951044008197
  • daid: 383
  • pt_3rd_aid: 100497308

为了保证每次使用的正确性,我们进行多次刷新查看,

  • appid: 716027609
  • e: 2
  • l: M
  • s: 3
  • d: 72
  • v: 4
  • t: 0.7970151752745949
  • daid: 383
  • pt_3rd_aid: 100497308

我们发现变化的参数只有一个 t 参数,研究研究 t 参数能不能正常访问。
打开postman工具,新建一个requests查询将url和params给进去发现正常获得二维码。

那我们暂且认为 t 参数并不是一个加密参数,姑且当 在0到1之间的随机数 带入。
t 参数转变 Python 语法为random.random()

编写代码

## 伪代码
self.cur_path = os.getcwd()
params = { 
    'appid': '716027609',
     'e': '2',
     'l': 'M',
     's': '3',
     'd': '72',
     'v': '4',
     't': str(random.random()),
     'daid': '383',
	'pt_3rd_aid': '100497308',
}
response = self.session.get(self.ptqrshow_url, params=params)
saveImage(response.content, os.path.join(self.cur_path, 'qrcode.jpg'))
showImage(os.path.join(self.cur_path, 'qrcode.jpg'))

登陆抓包准备

为了防止包过多,我们将曾经抓到的包清除掉并点回ALL界面。

点击登陆跳转,但此时我们需要查看数据包的状态,因为你登陆之后会出现302跳转现象,如果不截止抓包的话跳转后数据包将会清空。

我们首先要了解标红的两个按钮作用

  • 左上角按钮能够控制浏览器的抓包状态,如果将它点为灰色的话,浏览器将停止抓包固定住抓包的数量和位置并不会清空。
  • 其次按钮为改变浏览器的运行速率,如果出现网速过快现象使得抓包来不及按,我们可以将前后端发送速率改为缓慢3G网速,这样就能轻松点到截止抓包了。(手速慢才会用这个,比如我)

    我们拦截到这些登陆包,一个个寻找登陆所需要的主要包。
    关于登陆包只有一个URL为https://ssl.ptlogin2.qq.com/ptqrlogin
    参数为:

  • u1: https://graph.qq.com/oauth2.0/login_jump
  • ptqrtoken: 1506487176
  • ptredirect: 0
  • h: 1
  • t: 1
  • g: 1
  • from_ui: 1
  • ptlang: 2052
  • action: 1-0-1607136616096
  • js_ver: 20102616
  • js_type: 1
  • login_sig:
  • pt_uistyle: 40
  • aid: 716027609
  • daid: 383
  • pt_3rd_aid: 100497308

继续多次访问,我们发现ptqrtokenactionlogin_sig是可变的。
根据长度与16开头的字符串可变,盲猜action变量第三位为时间戳的倍数。
随意打开一个时间戳网址丢入该变量参数,发现扩大了一千倍。
action变量用Python编写为'action': '0-0-%s' % int(time.time() * 1000)

棘手的可变加密参数

第一个参数

我们正常打开该开发者窗口,准备查找加密参数位置。

点击Initiator 表盘,在这里我们能够找到每个参数来源,直接点入第一个loadScript之中。

我们发现我们获得了一串未格式化Javascript代码。
随意打开一个在线格式化的网站,将全部代码格式化之后在线查询一下加密参数在这里是经历了什么加密。

params.ptqrtoken=$.str.hash33($.cookie.get("qrsig"))
pt.ptui.login_sig=pt.ptui.login_sig||$.cookie.get("pt_login_sig");

我们获得了这俩加密参数的来源,看来都是关于cookie的加密。

  • ptqrtoken参数需要获取cookie中的qrsig键的值信息后经过hash33加密处理。
  • login_sig参数需要获取cookie中的pt_login_sig键的值信息即可。

既然找到加密的位置了,那我们就开始寻找cookie了。
出现这两个参数的可能地方并不多,我们不需要每个返回结果都需要看。

  • 一个是点击登陆按钮出现弹窗那一刻有可能出现该参数。
  • 一个是弹出二维码或QQ登陆信息时有可能出现该参数。

重新刷新后找到弹出登陆框的返回信息。
是个GET请求,URL为https://xui.ptlogin2.qq.com/cgi-bin/xlogin

参数为:

  • appid: 716027609
  • daid: 383
  • style: 33
  • login_text: 授权并登录
  • hide_title_bar: 1
  • hide_border: 1
  • target: self
  • s_url: https://graph.qq.com/oauth2.0/login_jump
  • pt_3rd_aid: 100497308
  • pt_feedback_link: https://support.qq.com/products/77942?customInfo=.appid100497308

为了保险,多次刷新查看是否含有另外的加密参数。
幸好幸好,都是正常死参数,好的直接访问。

编写代码

session = requests.Session()
params = { 
    'appid': '716027609',
    'daid': '383',
    'style': '33',
    'login_text': '授权并登录',
    'hide_title_bar': '1',
    'hide_border': '1',
    'target': 'self',
    's_url': 'https://graph.qq.com/oauth2.0/login_jump',
    'pt_3rd_aid': '100497308',
    'pt_feedback_link': 'https://support.qq.com/products/77942?customInfo=.appid100497308',
}
response = session.get('https://xui.ptlogin2.qq.com/cgi-bin/xlogin?', params=params)
cookie = session.cookies
print(cookie)
### 为了好看在这里我给全都拆开看了。
# -> <RequestsCookieJar[
# -> <Cookie pt_clientip=1c1e24098914080000b07d1bd433ca8b619275ff for .ptlogin2.qq.com/>, 
# -> <Cookie pt_guid_sig=f1d1eef00c25d5c6c6d8e2e991cb8b4f64bf619e97d242388d48887e4f0f93bf for .ptlogin2.qq.com/>, 
# -> <Cookie pt_local_token=49508773 for .ptlogin2.qq.com/>, 
# -> <Cookie pt_login_sig=BHH8t2gdwTlUjkRWg9xJ*vKp2v2-okQSrOV1q1QEyg*Z2uAbsqi18eiy*af*rvsb for .ptlogin2.qq.com/>, 
# -> <Cookie pt_serverip=8b6a647434394161 for .ptlogin2.qq.com/>, 
# -> <Cookie uikey=577ec007b515f37b7134decd61590dac2f03d036848870f20fe81c87cf7d7a95 for .ptlogin2.qq.com/>]>

运行之后,我们发现了pt_login_sig参数,直接字典拿到这个参数命名变量保存起来。

第二个参数 1.获取

既然第一个参数在登陆框内,那么盲猜第二个参数应该就是在二维码中保存着了。
刚才已经拿到了二维码的代码编写。话不多说直接拿cookie

编写代码

session = requests.Session()
params = { 
    'appid': '716027609',
    'e': '2',
    'l': 'M',
    's': '3',
    'd': '72',
    'v': '4',
    't': str(random.random()),
    'daid': '383',
    'pt_3rd_aid': '100497308',
}
response = session.get('https://ssl.ptlogin2.qq.com/ptqrshow?', params=params)
cookie = session.cookies
print(cookie)
# -> <RequestsCookieJar[
# -> <Cookie qrsig=4tlVhzwYo0FHzGeuen5Y-h5reR5cO*HjDyRQXcPedS*7MmOIYRENCN*BwY9JY1dD for .ptlogin2.qq.com/>]>

就一个真好,正好是我们想要的qrsig,使用字典get提取该键的值信息,这个就这么简单的拿到了。

第二个参数hash33加密

我们拿到的这个加密参数并不是可以直接给入代码中的,我们还得获得该hash33加密的东西才可以。
点击Search后搜索hash33查询。只有一个信息点进去查找该代码。

hash33加密算法Javascript版:

hash33: function hash33(str) { 
    var hash = 0;
    for (var i = 0, length = str.length; i < length; ++i) { 
        hash += (hash << 5) + str.charCodeAt(i)
    }
    return hash & 2147483647
}

编写为Python程序:

'''qrsig转ptqrtoken, hash33函数'''
def __decryptQrsig(self, qrsig):
    e = 0
    for c in qrsig:
        e += (e << 5) + ord(c)
    return 2147483647 & e

在此,所有的加密均获取,访问登陆URL即可获取session信息。

全部代码

import os,sys,time
import subprocess
import random
import re
import requests
def showImage(img_path):
try:
if sys.platform.find('darwin') >= 0: subprocess.call(['open', img_path])
elif sys.platform.find('linux') >= 0: subprocess.call(['xdg-open', img_path])
else: os.startfile(img_path)
except:
from PIL import Image
img = Image.open(img_path)
img.show()
img.close()
def removeImage(img_path):
if sys.platform.find('darwin') >= 0:
os.system("osascript -e 'quit app \"Preview\"'")
os.remove(img_path)
def saveImage(img, img_path):
if os.path.isfile(img_path):
os.remove(img_path)
fp = open(img_path, 'wb')
fp.write(img)
fp.close()
class qqmusicScanqr():
is_callable = True
def __init__(self, **kwargs):
for key, value in kwargs.items(): setattr(self, key, value)
self.info = 'login in qqmusic in scanqr mode'
self.cur_path = os.getcwd()
self.session = requests.Session()
self.__initialize()
'''登录函数'''
def login(self, username='', password='', crack_captcha_func=None, **kwargs):
# 设置代理
self.session.proxies.update(kwargs.get('proxies', { }))
# 获得pt_login_sig
params = { 
'appid': '716027609',
'daid': '383',
'style': '33',
'login_text': '授权并登录',
'hide_title_bar': '1',
'hide_border': '1',
'target': 'self',
's_url': 'https://graph.qq.com/oauth2.0/login_jump',
'pt_3rd_aid': '100497308',
'pt_feedback_link': 'https://support.qq.com/products/77942?customInfo=.appid100497308',
}
response = self.session.get(self.xlogin_url, params=params)
pt_login_sig = self.session.cookies.get('pt_login_sig')
# 获取二维码
params = { 
'appid': '716027609',
'e': '2',
'l': 'M',
's': '3',
'd': '72',
'v': '4',
't': str(random.random()),
'daid': '383',
'pt_3rd_aid': '100497308',
}
response = self.session.get(self.ptqrshow_url, params=params)
saveImage(response.content, os.path.join(self.cur_path, 'qrcode.jpg'))
showImage(os.path.join(self.cur_path, 'qrcode.jpg'))
qrsig = self.session.cookies.get('qrsig')
ptqrtoken = self.__decryptQrsig(qrsig)
# 检测二维码状态
while True:
params = { 
'u1': 'https://graph.qq.com/oauth2.0/login_jump',
'ptqrtoken': ptqrtoken,
'ptredirect': '0',
'h': '1',
't': '1',
'g': '1',
'from_ui': '1',
'ptlang': '2052',
'action': '0-0-%s' % int(time.time() * 1000),
'js_ver': '20102616',
'js_type': '1',
'login_sig': pt_login_sig,
'pt_uistyle': '40',
'aid': '716027609',
'daid': '383',
'pt_3rd_aid': '100497308',
'has_onekey': '1',
}
response = self.session.get(self.ptqrlogin_url, params=params)
print(response.text)
if '二维码未失效' in response.text or '二维码认证中' in response.text:pass
elif '二维码已经失效' in response.text:
raise RuntimeError('Fail to login, qrcode has expired')
else:break
time.sleep(0.5)
removeImage(os.path.join(self.cur_path, 'qrcode.jpg'))
# 登录成功
qq_number = re.findall(r'&uin=(.+?)&service', response.text)[0]
url_refresh = re.findall(r"'(https:.*?)'", response.text)[0]
response = self.session.get(url_refresh, allow_redirects=False, verify=False)
print('账号「%s」登陆成功' % qq_number)
return self.session
'''qrsig转ptqrtoken, hash33函数'''
def __decryptQrsig(self, qrsig):
e = 0
for c in qrsig:
e += (e << 5) + ord(c)
return 2147483647 & e
'''初始化'''
def __initialize(self):
self.headers = { 
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36',
}
self.ptqrshow_url = 'https://ssl.ptlogin2.qq.com/ptqrshow?'
self.xlogin_url = 'https://xui.ptlogin2.qq.com/cgi-bin/xlogin?'
self.ptqrlogin_url = 'https://ssl.ptlogin2.qq.com/ptqrlogin?'
self.session.headers.update(self.headers)
qq_login = qqmusicScanqr()
session = qq_login.login()

本文地址:https://blog.csdn.net/qq_45414559/article/details/110677428

(0)
上一篇 2022年3月22日
下一篇 2022年3月22日

相关推荐