Python扫码登录保存和验证cookies值——视频号篇(七)

python实现扫码登录微信视频号网页版

  • 一、找到相关链接网址
      • 1.找出需要的网址和参数
      • 2.接着在小编在index.a2de8d0b.js找到这一段代码
      • 3.利用python的import qrcode对这段网址文字信息生成二维码图片,进行扫码操作
  • 二、确认链接网址,登录测试
  • 三、验证cookie值是否有效
  • 四、保存cookie的方法
  • 五、保存cookies值并进行验证完整代码
      • 完整代码
  • 六 、 更多文章

一、找到相关链接网址

  • 其实视频号扫码登录和上一篇B站的很相似,都是没有给出二维码网址的

1.找出需要的网址和参数

网址:https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/auth/auth_login_code
参数:token

session = requests.session()
loginurl = 'https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/auth/auth_login_code'
urldata = session.post(loginurl,data={
     "timestamp":"1615173741493","_log_finder_id":'null',"rawKeyBuff":'null'}, headers=headers).json()
#输出urldata = {'errCode': 0, 'errMsg': 'request successful', 'data': {'token': 'AQ……'}}
  • 获取了上面访问获得了参数token的值

2.接着在小编在index.a2de8d0b.js找到这一段代码

while (1)
    switch(t.prev = t.next) {
     
        case
    0:
    return t.next = 2,
    gr["a"].getLoginToken();
case
2:
e = t.sent,
n = e.data,
n ? (this.token = n.token,
i = "".concat(location.origin, "/mobile/confirm.html"),
    this.genQrcode("".concat(i, "?token=").concat(this.token)),
    this.pollLoginStatus()): vt["b"].warn("获取登录二维码失败");
case
5:
case
"end":
return t.stop()
}
  • 可以确认隐藏在二维码里面的文字信息,pngurl就是二维码隐藏的文字信息
session = requests.session()
loginurl = 'https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/auth/auth_login_code'
urldata = session.post(loginurl,data={
     "timestamp":"1615173741493","_log_finder_id":'null',"rawKeyBuff":'null'}, headers=headers).json()
pngurl = 'https://channels.weixin.qq.com/mobile/confirm.html?token={}'.format(urldata['data']['token'])
#输出pngurl = https://channels.weixin.qq.com/mobile/confirm.html?token=AQAAAD9R……

3.利用python的import qrcode对这段网址文字信息生成二维码图片,进行扫码操作

session = requests.session()
loginurl = 'https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/auth/auth_login_code'
urldata = session.post(loginurl,data={
     "timestamp":"1615173741493","_log_finder_id":'null',"rawKeyBuff":'null'}, headers=headers).json()
pngurl = 'https://channels.weixin.qq.com/mobile/confirm.html?token={}'.format(urldata['data']['token'])

#生成二维码并进行缓存,
qr = qrcode.QRCode()
qr.add_data(pngurl)
img = qr.make_image()
#缓存的好处就是不需要保存本地
a = BytesIO()
img.save(a, 'png')
png = a.getvalue()
a.close()
#打开二维码进行扫码操作
t = showpng(png)
t.start()

二、确认链接网址,登录测试

  • 扫码结束就需要确认的链接,这个网址很容易找到

网址:https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/auth/auth_login_status?token={}×tamp={}
输出:{‘errCode’: 0, ‘data’: {‘status’: 0, ‘acctStatus’: 0}}

  • 带进参数获得不同数值

‘status’: 0:未扫码
‘status’: 5:已扫码,未确认
‘status’: 1:已确认,登录成功!

tokenurl = 'https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/auth/auth_login_status?token={}×tamp={}'
while 1:
    dataurl = session.post(tokenurl.format(token,time.time()*1000), headers=headers).json()
    if '0' in str(dataurl['data']['status']):
        print('二维码未失效,请扫码!')
    elif '5' in str(dataurl['data']['status']):
        print('已扫码,请确认!')
    elif '0' in str(dataurl['data']['status']):
        print('二维码已失效,请重新运行!')
    elif '1' in str(dataurl['data']['status']):
        print('已确认,登入成功!')
        break
    else:
        print('其他:', dataurl)
    time.sleep(2)
  • 确认以后,cookie值就获取到了,没有其他的了,比较简单。

  • 修改:(经过小编后面采集列表时发现现有cookie值权限有限,还需要先读出rawKeyBufflog_finder_id这两个值,才能访问视频列表!)

  • 读出这两个值的两个网址

  • https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/auth/auth_finder_list

  • https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/auth/auth_set_finder

  • 修改代码为:

tokenurl = 'https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/auth/auth_login_status?token={}×tamp={}'
while 1:
    dataurl = session.post(tokenurl.format(token, int(time.time() * 1000)), headers=headers).json()
    if '0' in str(dataurl['data']['status']):
        print('二维码未失效,请扫码!')
    elif '5' in str(dataurl['data']['status']):
        print('已扫码,请确认!')
    elif '1' in str(dataurl['data']['status']):
    #这两个网址放在这里
        url = session.post('https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/auth/auth_finder_list', data={
     "timestamp": time.time() * 1000, "_log_finder_id": 'null', "rawKeyBuff": 'null'}, headers=headers).json()
        session.post('https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/auth/auth_set_finder', data={
     "finderUsername": url['data']['finderList'][0]['finderUsername'], "timestamp": int(time.time() * 1000), "_log_finder_id": 'null', "rawKeyBuff": 'null'}, headers=headers)
        print('已确认,登入成功!')
        break
    else:
        print('其他:', dataurl)
    time.sleep(2)
  • 这下才是完完整整的满权限的cookie值!!

三、验证cookie值是否有效

  • 其实找验证cookie方法很简单,一般情况就是上面确认后的下一个链接网址就是可以判断的

https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/auth/auth_finder_list

  • 要有个习惯,每次访问网址的之前要知道该网址是get还是post,不然老是报错不知道什么原因
def islogin(session):
    try:
        session.cookies.load(ignore_discard=True)
    except Exception:
        pass
    loginurl = session.post("https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/auth/auth_finder_list", data={
     "timestamp":time.time()*1000,"_log_finder_id":'null',"rawKeyBuff":'null'}, headers=headers).json()
    print(loginurl)
    if loginurl['errCode'] == 0:
        print('Cookies值有效,',loginurl['data']['finderList'][0]['nickname'],',已登录!')
        return session, True
    else:
        print('Cookies值已经失效,请重新扫码登录!')
        return session, False

四、保存cookie的方法

  • 保存cookie有两种方式

保存.cookie格式.txt格式

  • cookie格式的文件需要有专门编码的软件打开,用txt文本打开是一堆乱码
  • txt格式的文件就是纯文本格式,可以正常打开

cookie比较有优势,因为经过小编不断论证发现有些平台扫码过后用txt保存的话读取不到cookie,而用cookie格式保存就可以读取保存,而且读取cookie信息更加全面

  • 下面两种方式,以后一般就用cookie格式来保持,防止报错读取不到cookie

cookie格式

    session = requests.session()
    if not os.path.exists('xxx.cookie'):
        with open('xxx.cookie', 'wb') as f:
            pickle.dump(session.cookies, f)
    # 读取
    session.cookies = pickle.load(open('xxx.cookie', 'rb'))
    session, status = islogin(session)

#while后面还需要再加一段
        with open('xxx.cookie', 'wb') as f:
            pickle.dump(session.cookies, f)

TXT格式

    if not os.path.exists('xxx.txt'):
        with open("xxx.txt", 'w') as f:
            f.write("")
    session = requests.session()
    session.cookies = cookielib.LWPCookieJar(filename='xxx.txt')
    session, status = islogin(session)
#while后面还需要再加一段
session.cookies.save()
  • 用法可以参考下面完整代码

五、保存cookies值并进行验证完整代码

完整代码

# -*- coding: utf-8 -*-
import pickle
import agent
from threading import Thread
import time
import requests
from io import BytesIO
import os
from PIL import Image
import qrcode
requests.packages.urllib3.disable_warnings()

headers = {
     'User-Agent': agent.get_user_agents()}

class showpng(Thread):
    def __init__(self, data):
        Thread.__init__(self)
        self.data = data

    def run(self):
        img = Image.open(BytesIO(self.data))
        img.show()

def islogin(session):
    try:
        session.cookies.load(ignore_discard=True)
    except Exception:
        pass
    loginurl = session.post("https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/auth/auth_finder_list", data={
     "timestamp":int(time.time()*1000),"_log_finder_id":'null',"rawKeyBuff":'null'}, headers=headers).json()
    if loginurl['errCode'] == 0:
        print('Cookies值有效,',loginurl['data']['finderList'][0]['nickname'],',已登录!')
        return session, True
    else:
        print('Cookies值已经失效,请重新扫码登录!')
        return session, False


def sphlogin():
    # 写入
    session = requests.session()
    if not os.path.exists('sphcookies.cookie'):
        with open('sphcookies.cookie', 'wb') as f:
            pickle.dump(session.cookies, f)
    # 读取
    session.cookies = pickle.load(open('sphcookies.cookie', 'rb'))
    session, status = islogin(session)
    if not status:
        loginurl = 'https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/auth/auth_login_code'
        urldata = session.post(loginurl, data={
     "timestamp":int(time.time() * 1000), "_log_finder_id": 'null', "rawKeyBuff": 'null'}, headers=headers).json()
        token = urldata['data']['token']
        pngurl = 'https://channels.weixin.qq.com/mobile/confirm.html?token={}'.format(token)
        qr = qrcode.QRCode()
        qr.add_data(pngurl)
        img = qr.make_image()
        a = BytesIO()
        img.save(a, 'png')
        png = a.getvalue()
        a.close()
        t = showpng(png)
        t.start()
        tokenurl = 'https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/auth/auth_login_status?token={}×tamp={}'
        while 1:
            dataurl = session.post(tokenurl.format(token, int(time.time() * 1000)), headers=headers).json()
            if '0' in str(dataurl['data']['status']):
                print('二维码未失效,请扫码!')
            elif '5' in str(dataurl['data']['status']):
                print('已扫码,请确认!')
            elif '1' in str(dataurl['data']['status']):
                url = session.post('https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/auth/auth_finder_list', data={
     "timestamp": time.time() * 1000, "_log_finder_id": 'null', "rawKeyBuff": 'null'}, headers=headers).json()
                session.post('https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/auth/auth_set_finder', data={
     "finderUsername": url['data']['finderList'][0]['finderUsername'], "timestamp": int(time.time() * 1000), "_log_finder_id": 'null', "rawKeyBuff": 'null'}, headers=headers)
                print('已确认,登入成功!')
                break
            else:
                print('其他:', dataurl)
            time.sleep(2)
        with open('sphcookies.cookie', 'wb') as f:
            pickle.dump(session.cookies, f)
    return session

if __name__ == '__main__':
    sphlogin()

  • import agent 文件可以到第抖音篇查看

六 、 更多文章

  1. 抖音篇(一)
  2. 快手篇(二)
  3. 微视篇(三)
  4. 微信公众号篇(四)
  5. 微博篇(五))
  6. B站篇(六))
  7. CSDN篇(八)
  8. 网易云音乐篇(九)
  • 后期小编将开设登录后批量采集各平台数据(点赞、播放量、评论、图片、视频、音乐等)专栏文章!记得关注哟!
  • 如果文章能帮到您,愿意给小编点个 吗,么么哒~ (●’◡’●)
  • 数据采集篇

Python采集后台数据图片视频音乐:视频号(一)

你可能感兴趣的:(Python实现扫码登录,python,cookie)