Requests学习之模拟登录教务(强智)

import time
import requests
import winreg
from PIL import Image
import threading
import os


URL = "jw.wfu.edu.cn"  # 学校教务域名,不需要带http://以及末尾的/


# 获取桌面路径
def desktop():
    key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders',)
    return winreg.QueryValueEx(key, "Desktop")[0]


# 登陆方法
def login_jw(usr, psw):
    cookie = requests.get(f"http://{URL}/").cookies.get_dict()  # 获取cookie
    image = requests.get(url=f"http://{URL}/verifycode.servlet", cookies=cookie).content  # 获取验证码
    with open(f"{desktop()}\\验证码.jpg", "wb") as f:  # 为了查看方便将验证码放在桌面上
        f.write(image)
        f.close()

    # 打开验证码
    def open_pic():
        time.sleep(0.5)  # 防止读写冲突
        img = Image.open(f"{desktop()}\\验证码.jpg", "r")
        img.show()
    t = threading.Thread(target=open_pic, args=())  # 创建线程打开图片
    t.start()

    res = requests.post(f"http://{URL}/Logon.do?method=logon&flag=sess", cookies=cookie).text  # 获取加密所需要的字符
    string = res.split("#")
    code = string[0]
    sxh = string[1]
    data = usr + "%%%" + psw
    box = ""  # 装加密后的字符串容器
    b = 0  # 计未取code的位置
    for a in range(len(code)):
        if a < 20:
            if len(data) > a:
                box = box + data[a]
            for c in range(int(sxh[a])):
                box = box + code[b]
                b += 1
        else:
            box = box + data[20:]
            break
        a += 1
    # 准备post发送的数据
    data = {
        'userAccount': '',
        'userPassword': '',
        "RANDOMCODE": input("验证码:"),
        "encoded": box,
    }
    res = requests.post(url=f"http://{URL}/Logon.do?method=logon", data=data, cookies=cookie, allow_redirects=False)  #发送登录请求
    # 尝试找到302地址,如果有则打印并返回1,如果出错则返回0
    try:
        print(res.headers['Location'])
        return 1
    except KeyError:   # 打印并获取错误信息
        slecter = html.fromstring(res.text)
        x = slecter.xpath('//li[@id="showMsg"]/text()')
        x = x[0].replace("\n", "").replace("    ", "").replace(" ", "").replace("\r", "")
        print(x)   
        return 0


if __name__ == '__main__':
    while True:
        if login_jw(usr="学号", psw="密码"):
            break
    print("ok!")
    os.remove(f"{desktop()}\\验证码.jpg")  # 删除图片

标签: requests

文档最后编辑于4年前

评论

评论已关闭

小小英雄杜恩

子曰:“弟子入则孝,出则弟,谨而信,泛爱众,而亲仁。行有余力,则以学文。”


:D 获取中...