Python模拟登陆 —— 征服验证码 8 微信网页版

简介: 微信登录界面微信网页版使用了UUID含义是通用唯一识别码来保证二维码的唯一性。先用一个伪造的appid获得uuid。params = { 'appid': 'wx782c26e4c19acffb', 'fun': 'new', 'lang': 'zh_CN', '_': int(time.time()), }不伪造的话,会有400错误,拿不到uuid。
img_9b95be5ebdb1e790a95c67de273ff9e6.png
微信登录界面

微信网页版使用了UUID含义是通用唯一识别码来保证二维码的唯一性。
先用一个伪造的appid获得uuid。

params = {
        'appid': 'wx782c26e4c19acffb',
        'fun': 'new',
        'lang': 'zh_CN',
        '_': int(time.time()),
    }

不伪造的话,会有400错误,拿不到uuid。

img_0461e8b94a61e2daac6bf39e3be2785a.png

二维码在网页源代码也是查不到的,这时就需要uuid了。

url = 'https://login.weixin.qq.com/qrcode/' + uuid

微信的登录需要多次请求数据,并根据返回的数据进行提取。
扫码成功的返回如果是200,证明扫码成功。

然后需要模拟微信的初始化同步过程。

同步完成之后,打印通信录。

微信确实复杂!这么做的话不留下cookie,提高了安全性。web QQ的原理也差不多,毕竟一家做的。

import os
import re
import time
import sys
import subprocess
import requests
import xml.dom.minidom
import json

session = requests.session()
headers = {
    'User-Agent' : 'Mozilla/5.0 (Windows NT 5.1; rv:33.0) Gecko/20100101 Firefox/33.0'
}

QRImgPath = os.path.split(os.path.realpath(__file__))[0] + os.sep + 'webWeixinQr.jpg'
uuid = ''
tip = 0
base_uri = ''
redirect_uri = ''
skey = ''
wxsid = ''
wxuin = ''
pass_ticket = ''
deviceId = 'e000000000000000'
BaseRequest = {}
ContactList = []
My = []
SyncKey = ''


def getUUID():
    global uuid,session

    url = 'https://login.weixin.qq.com/jslogin'
    params = {
        'appid': 'wx782c26e4c19acffb',
        'fun': 'new',
        'lang': 'zh_CN',
        '_': int(time.time()),
    }

    response = session.get(url, params=params)
    data = response.content.decode('utf-8')
    # print(data) >>> window.QRLogin.code = 200; window.QRLogin.uuid = "oZwt_bFfRg==";

    regx = r'window.QRLogin.code = (\d+); window.QRLogin.uuid = "(\S+?)"'
    pm = re.search(regx, data)

    code = pm.group(1)
    uuid = pm.group(2)

    if code == '200':
        return True

    return False


def showQRImage():
    global tip

    url = 'https://login.weixin.qq.com/qrcode/' + uuid
    params = {
        't': 'webwx',
        '_': int(time.time()),
    }

    response = session.get(url, params=params)

    tip = 1

    with open(QRImgPath, 'wb') as f:
        f.write(response.content)
        f.close()

    if sys.platform.find('darwin') >= 0:
        subprocess.call(['open', QRImgPath])
    elif sys.platform.find('linux') >= 0:
        subprocess.call(['xdg-open', QRImgPath])
    else:
        os.startfile(QRImgPath)

    print('请使用微信扫描二维码以登录')


def waitForLogin():
    global tip, base_uri, redirect_uri

    url = 'https://login.weixin.qq.com/cgi-bin/mmwebwx-bin/login?tip=%s&uuid=%s&_=%s' % (
        tip, uuid, int(time.time()))

    response = session.get(url)
    data = response.content.decode('utf-8')

    # print(data)

    # window.code=500;
    regx = r'window.code=(\d+);'
    pm = re.search(regx, data)

    code = pm.group(1)

    if code == '201':  # 已扫描
        print('成功扫描,请在手机上点击确认以登录')
        tip = 0
    elif code == '200':  # 已登录
        print('正在登录...')
        regx = r'window.redirect_uri="(\S+?)";'
        pm = re.search(regx, data)
        redirect_uri = pm.group(1) + '&fun=new'
        base_uri = redirect_uri[:redirect_uri.rfind('/')]

        # closeQRImage
        if sys.platform.find('darwin') >= 0:  # for OSX with Preview
            os.system("osascript -e 'quit app \"Preview\"'")
    elif code == '408':  # 超时
        pass
    # elif code == '400' or code == '500':

    return code


def login():
    global skey, wxsid, wxuin, pass_ticket, BaseRequest

    response = session.get(redirect_uri)
    data = response.content.decode('utf-8')

    # print(data)

    '''
        <error>
            <ret>0</ret>
            <message>OK</message>
            <skey>xxx</skey>
            <wxsid>xxx</wxsid>
            <wxuin>xxx</wxuin>
            <pass_ticket>xxx</pass_ticket>
            <isgrayscale>1</isgrayscale>
        </error>
    '''
    xml.dom
    doc = xml.dom.minidom.parseString(data)
    root = doc.documentElement

    for node in root.childNodes:
        if node.nodeName == 'skey':
            skey = node.childNodes[0].data
        elif node.nodeName == 'wxsid':
            wxsid = node.childNodes[0].data
        elif node.nodeName == 'wxuin':
            wxuin = node.childNodes[0].data
        elif node.nodeName == 'pass_ticket':
            pass_ticket = node.childNodes[0].data

    # print('skey: %s, wxsid: %s, wxuin: %s, pass_ticket: %s' % (skey, wxsid,
    # wxuin, pass_ticket))

    if not all((skey, wxsid, wxuin, pass_ticket)):
        return False

    BaseRequest = {
        'Uin': int(wxuin),
        'Sid': wxsid,
        'Skey': skey,
        'DeviceID': deviceId,
    }

    return True


def webwxinit():

    url = base_uri + \
        '/webwxinit?pass_ticket=%s&skey=%s&r=%s' % (
            pass_ticket, skey, int(time.time()))
    params = {
        'BaseRequest': BaseRequest
    }

    h = headers
    h['ContentType'] = 'application/json; charset=UTF-8'
    response = session.post(url, data=json.dumps(params), headers=h)
    data = response.content.decode('utf-8')
    #print(data)

    global ContactList, My, SyncKey

    dic = json.loads(data)
    ContactList = dic['ContactList']
    My = dic['User']

    SyncKeyList = []
    for item in dic['SyncKey']['List']:
        SyncKeyList.append('%s_%s' % (item['Key'], item['Val']))
    SyncKey = '|'.join(SyncKeyList)

    ErrMsg = dic['BaseResponse']['ErrMsg']

    Ret = dic['BaseResponse']['Ret']
    if Ret != 0:
        return False

    return True


def webwxgetcontact():

    url = base_uri + \
        '/webwxgetcontact?pass_ticket=%s&skey=%s&r=%s' % (
            pass_ticket, skey, int(time.time()))

    h = headers
    h['ContentType'] = 'application/json; charset=UTF-8'
    response = session.get(url, headers=h)
    data = response.content.decode('utf-8')
    # print(data)

    dic = json.loads(data)
    MemberList = dic['MemberList']

    # 倒序遍历,不然删除的时候出问题..
    SpecialUsers = ["newsapp", "fmessage", "filehelper", "weibo", "qqmail", "tmessage", "qmessage", "qqsync", "floatbottle", "lbsapp", "shakeapp", "medianote", "qqfriend", "readerapp", "blogapp", "facebookapp", "masssendapp",
                    "meishiapp", "feedsapp", "voip", "blogappweixin", "weixin", "brandsessionholder", "weixinreminder", "wxid_novlwrv3lqwv11", "gh_22b87fa7cb3c", "officialaccounts", "notification_messages", "wxitil", "userexperience_alarm"]
    for i in range(len(MemberList) - 1, -1, -1):
        Member = MemberList[i]
        if Member['VerifyFlag'] & 8 != 0:  # 公众号/服务号
            MemberList.remove(Member)
        elif Member['UserName'] in SpecialUsers:  # 特殊账号
            MemberList.remove(Member)
        elif Member['UserName'].find('@@') != -1:  # 群聊
            MemberList.remove(Member)
        elif Member['UserName'] == My['UserName']:  # 自己
            MemberList.remove(Member)

    return MemberList

def main():

    if not getUUID():
        print('获取uuid失败')
        return

    showQRImage()
    time.sleep(1)

    while waitForLogin() != '200':
        pass

    os.remove(QRImgPath)

    if not login():
        print('登录失败')
        return
    #登录完成, 下面查询好友
    if not webwxinit():
        print('初始化失败')
        return

    MemberList = webwxgetcontact()

    print('通讯录共%s位好友' % len(MemberList))

    for x in MemberList :
        sex = '未知' if x['Sex'] == 0 else '男' if x['Sex'] == 1 else '女'
        print('昵称:%s, 性别:%s, 备注:%s, 签名:%s' % (x['NickName'], sex, x['RemarkName'], x['Signature']))





if __name__ == '__main__':
    print('开始')
    main()
目录
相关文章
|
7天前
|
数据采集 存储 API
网络爬虫与数据采集:使用Python自动化获取网页数据
【4月更文挑战第12天】本文介绍了Python网络爬虫的基础知识,包括网络爬虫概念(请求网页、解析、存储数据和处理异常)和Python常用的爬虫库requests(发送HTTP请求)与BeautifulSoup(解析HTML)。通过基本流程示例展示了如何导入库、发送请求、解析网页、提取数据、存储数据及处理异常。还提到了Python爬虫的实际应用,如获取新闻数据和商品信息。
|
1月前
|
数据库 开发者 Python
用Python代码打造你的私人网页交互系统
用Python代码打造你的私人网页交互系统
27 1
|
1月前
|
数据采集 机器学习/深度学习 安全
Python爬虫之极验滑动验证码的识别
了解极验滑动验证码、特点、识别思路、初始化、模拟点击、识别缺口、模拟拖动。
59 0
|
2月前
|
数据采集 存储 前端开发
Python爬虫实战:动态网页数据抓取与分析
本文将介绍如何利用Python编写爬虫程序,实现对动态网页的数据抓取与分析。通过分析目标网站的结构和请求方式,我们可以利用Selenium等工具模拟浏览器行为,成功获取到需要的数据并进行进一步处理与展示。
|
1月前
|
数据采集 测试技术 API
python爬虫之app爬取-微信朋友圈
搭建appium环境,appium基本使用,API操作等等
72 0
|
7天前
|
开发者 索引 Python
实践:如何使用python在网页的表格里抓取信息
实践:如何使用python在网页的表格里抓取信息
|
7天前
|
数据采集 JSON 网络协议
「Python系列」Python urllib库(操作网页URL对网页的内容进行抓取处理)
`urllib` 是 Python 的一个标准库,用于打开和读取 URLs。它提供了一组模块,允许你以编程方式从网络获取数据,如网页内容、文件等。
29 0
|
1月前
|
Python
如何使用Python的Requests库进行网络请求和抓取网页数据?
如何使用Python的Requests库进行网络请求和抓取网页数据?
12 0
|
1月前
|
数据采集 存储 关系型数据库
Python爬虫-使用代理获取微信公众号文章
使用代理爬取微信公众号文章
50 0
|
1月前
|
数据采集 Web App开发 文字识别
Python爬虫之点触验证码的识别
点触验证码识别思路,初始化,获取,识别。
55 0
Python爬虫之点触验证码的识别

热门文章

最新文章