基于Python会话与requests库实现河北网络学院自动化

开发背景:

 鉴于上次使用selenium实现浏览器实现自动化较繁琐,因此本次在各位的鼓舞下开发基于requests库实现的无界面加密打包软件,轻松实现河北干部网络学院视频倍速!

代码逻辑:

本次软件开发使用模块化编程,并最终使用pyinstaller打包成exe文件,加入md5加密模块,可以让各位在基础薄弱的情况下进行软件的推广,特此申明:本软件及源代码仅用于网络学习交流,严禁用于商业用途,请各位在下载exe文件24小时内删除!

代码模块:

导入第三方库:

import random
import re
import sys
from hashlib import md5

import requests
from prettytable import PrettyTable
from tqdm import trange

import time

主函数模块:

def main():
    def encrypt_md5(s):
        # 创建md5对象
        new_md5 = md5()
        # 这里必须用encode()函数对字符串进行编码,不然会报 TypeError: Unicode-objects must be encoded before hashing
        new_md5.update(s.encode(encoding='GB2312', errors='ignore'))
        # 加密
        return new_md5.hexdigest()

    print('本软件不得用于商业用途,仅供学习交流!')
    print('作者tel:19520209298')
    print(''' ╭╩╮ ╔════╗╔════╗╔════╗╔════╗╔════╗╔════╗
╭╯GO╠╣支持 ╠╣比心╠╣爱你 ╠╣爱过╠╣请支持我 Mashuai
╰⊙═⊙╯╚◎══◎╝╚◎══◎╝╚◎══◎╝╚◎══◎╝╚◎══◎╝╚◎══◎╝''')
    print('------------------------------------------------------')
    time_stamp = time.time()
    time_array = time.localtime(time_stamp)  # 格式化时间戳为本地时间
    # 本地格式化时间
    format_time = time.strftime("%Y-%m-%d", time_array)
    print(f"当前日期为:{format_time}")
    key = encrypt_md5(format_time)
    key_press = input('请输入您所持有的密钥:')
    if key_press == key:
        print("密钥正确,成功进入系统......")
        login(getua())
    else:
        print("您的密钥有误,请联系作者获取正确密钥")
        time.sleep(3)
        sys.exit()
    while True:
        print('---------------------主功能菜单------------------------')
        print('1.进行课程报名')
        print('2.进行已报名课程学习')
        print('3.联系作者')
        print('0.退出软件')
        index = int(input('请选择您要使用的功能:'))
        if index == 1:
            enrollable()
        elif index == 2:
            get_lesson()
        elif index == 3:
            contact_wechat()
            contact_qq()
        elif index == 0:
            a = input('您是否确认退出? Y/N')
            if a == 'Y' or a == 'y':
                break
            else:
                print("您已取消,已返回主菜单")

联系方式模块:

def contact_wechat():
    print("微信:LOGO.MY1314")


def contact_qq():
    print("QQ:21194524\n邮箱:21194524@qq.com")

获取伪装请求头模块:

# 伪装请求头
def getua():
    url_ua = 'https://fake-useragent.herokuapp.com/browsers/0.1.11'
    print('正在伪装请求头User-Agent......')
    resp = requests.get(url_ua)
    dict_ua = resp.json()
    i = random.randint(0, 30)
    ua = dict_ua['browsers']['chrome'][i]
    return ua

获取登录个人信息模块:

# 获取登录信息
def login(ua):
    username = input('请输入您的用户名:')
    passwd = input('请输入您的密码:')
    print('伪装成功', ua)
    url_login = 'http://www.hebgb.gov.cn/portal/login_ajax.do'
    data = {
        "username": f"{username}",
        "passwd": f"{passwd}"
    }
    headers = {
        "Host": "www.hebgb.gov.cn",
        "Referer": "http://www.hebgb.gov.cn/",
        "User-Agent": f"{ua}"
    }
    # 登录请求
    a = session.post(url_login, data=data)
    if "错误" in a.text:
        print(a.text)
    millis = int(round(time.time() * 1000))
    url_getinfo = f'http://www.hebgb.gov.cn/portal/checkIsLogin.do?_={millis}'
    resp = session.get(url_getinfo)
    print('------------------------------------------------------')
    dict_info = resp.json()
    # 真实姓名
    realname = dict_info['realname']
    # 要求总学时
    yqzxs = dict_info['yqzxs']
    # 已完成学时
    ywczxs = dict_info['ywczxs']
    # 要求必修总学时
    yqbxxs = dict_info['yqbxxs']
    # 已完成必修总学时
    ywcbxxs = dict_info['ywcbxxs']
    print(f"欢迎您 {realname} 同志,\n"
          f"要求总学时为{yqzxs},已完成学时{ywczxs},\n"
          f"要求必修总学时为{yqbxxs},已完成必修总学时{ywcbxxs}")
获取可报名课程模块:
def enrollable():
    def choose():
        nonlocal result_1
        index_chose = int(input('请输入您想要报名的课程序号:')) - 1
        cid_choose = result_1[index_chose][0]
        url_chose = 'http://www.hebgb.gov.cn/student/class_register.do'
        params_choose = {
            "cid": f"{cid_choose}",
            "type": "1",
            "url": "learn"
        }
        resp_chose = session.get(url_chose, params=params_choose)
        regex_2 = re.compile(r'alert(.*?);', re.S)
        alert = regex_2.findall(resp_chose.text)
        print("报名状态为:", alert[0])

    global table
    url_enrollable = 'http://www.hebgb.gov.cn/student/class_notMyClassList.do?type=1&menu=myclass'
    resp_enrollable = session.get(url_enrollable)
    regex_1 = re.compile(r'"/portal/class_detail.do.*?&cid=(.*?)" title="(.*?)>', re.S)
    result_1 = regex_1.findall(resp_enrollable.text)
    print("成功获取到课程信息:")
    table = PrettyTable(['序号', 'cid', 'title'])
    for i in range(len(result_1)):
        table.add_row([i + 1, result_1[i][0], result_1[i][1]])
    if len(result_1) == 0:
        print(table)
        print("暂无可报名课程!")
    else:
        print(table)
        choose()
获取可以学习的课程模块:
def get_lesson():
    # 学习任务
    def job(id_course, rate, study_course, sumtime):
        headers = {
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
            "Accept-Encoding": "gzip,deflate",
            "Accept-Language": "zh-CN, zh;q=0.9",
            "Connection": "keep-alive",
            "Content-Length": "0",
            "Host": "www.hebgb.gov.cn",
            "Origin": "http://www.hebgb.gov.cn",
            "Referer": f"http://www.hebgb.gov.cn/portal/study_play.do?id={id_course}"
        }
        url = f'http://www.hebgb.gov.cn/portal/study_play.do?id={id_course}'
        session.get(url, headers=headers)
        number = int(int(sumtime) * 60 / rate)
        print("预计本节所需时长为", f"{int(int(sumtime) * 60 / rate)+1}秒")
        url_learn = f'http://www.hebgb.gov.cn/portal/seekNew.do'
        global count
        for k in trange(number + 1, ncols=100, desc=f'本章节学习进度'):
            time.sleep(1)
            time_stamp = time.time()
            time_array = time.localtime(time_stamp)  # 格式化时间戳为本地时间
            # 本地格式化时间
            format_time = time.strftime("%Y-%m-%d %H:%M:%S", time_array)
            res01 = {"lesson_location": f'{k * rate}', "session_time": 29, "last_learn_time": f"{format_time}"}
            dict_0 = {'res01': res01, 'last_study_sco': "res01"}
            data = {
                "id": f"{id_course}",
                "serializeSco": f'{dict_0}',
                "duration": f"{rate}",
                "study_course": f"{study_course}"
            }
            session.post(url_learn, data=data)
        print(f"章节:ID{study_course}  学习完成......")
        print('------------------------------------------------------')

    # 选择学习的课程
    def chose_lesson():
        index_lesson = int(input('请选择您需要学习的课程序号:'))
        lesson_cid = result_3[index_lesson - 1][0]
        lesson_name = result_3[index_lesson - 1][1]
        print('您选择的课程cid为:', lesson_cid)
        print('您选择的课程名称为:', lesson_name)
        return lesson_cid

    # 进行学习任务
    def get_chapter(lesson_cid):
        global count
        url_chapter = f'http://www.hebgb.gov.cn/student/class_detail_course.do?cid={lesson_cid}&elective_type=1&menu=myclass&tab_index=0'
        resp_chapter = session.get(url_chapter)
        regex_4 = re.compile(r'courseId=(.*?)".*?</i>(.*?) 分钟.*?\((.*?)\)"', re.S)
        result_4 = regex_4.findall(resp_chapter.text)
        if len(result_4) == 0:
            print("本课程已经过期,无法进行学习!")
        else:
            rate = int(input("请输入您需要的学习倍率(数字):"))
            for ids in result_4:
                id_course = ids[2]
                study_course = ids[0]
                sumtime = ids[1]
                print(f"正在学习第{count}节,总时长为{sumtime}分钟,")
                job(id_course, rate, study_course, sumtime)
                count += 1
            print('学习完成,已自动返回主菜单......')

    url_lesson = 'http://www.hebgb.gov.cn/student/class_myClassList.do?type=1&menu=myclass'
    resp_lesson = session.get(url_lesson)
    regex_3 = re.compile('.*?cid=(.*?)&elective_type=1&menu=myclass&tab_index=0" title="(.*?)">')
    result_3 = regex_3.findall(resp_lesson.text)
    table_0 = PrettyTable(('序号', 'cid', 'title'))
    for j in range(len(result_3)):
        table_0.add_row((j + 1, result_3[j][0], result_3[j][1]))
    print(table_0)
    if len(result_3) == 0:
        print("未查询到可学习课程,请进行报名!")
    else:
        get_chapter(chose_lesson())

main字段:

if __name__ == '__main__':
    count = 1
    session = requests.Session()
    try:
        main()
    except Exception as e:
        print("错误信息:",e)
        print("请检查您输入的内容是否合法!")
        print("若非用户因素,将报错截图发送至作者VX,供作者优化程序!")
        time.sleep(3)

 全代码:

# coding: utf-8
# coding:unicode_escape
# @Time    : 2022/9/7 8:38
# @Author  : Mashuai
# @File    : Cyber Academy.py
# @Software: PyCharm
import random
import re
import sys
from hashlib import md5

import requests
from prettytable import PrettyTable
from tqdm import trange

import time


# 主函数
def main():
    def encrypt_md5(s):
        # 创建md5对象
        new_md5 = md5()
        # 这里必须用encode()函数对字符串进行编码,不然会报 TypeError: Unicode-objects must be encoded before hashing
        new_md5.update(s.encode(encoding='GB2312', errors='ignore'))
        # 加密
        return new_md5.hexdigest()

    print('本软件不得用于商业用途,仅供学习交流!')
    print('作者tel:19520209298')
    print(''' ╭╩╮ ╔════╗╔════╗╔════╗╔════╗╔════╗╔════╗
╭╯GO╠╣支持 ╠╣比心╠╣爱你 ╠╣爱过╠╣请支持我 Mashuai
╰⊙═⊙╯╚◎══◎╝╚◎══◎╝╚◎══◎╝╚◎══◎╝╚◎══◎╝╚◎══◎╝''')
    print('------------------------------------------------------')
    time_stamp = time.time()
    time_array = time.localtime(time_stamp)  # 格式化时间戳为本地时间
    # 本地格式化时间
    format_time = time.strftime("%Y-%m-%d", time_array)
    print(f"当前日期为:{format_time}")
    key = encrypt_md5(format_time)
    key_press = input('请输入您所持有的密钥:')
    if key_press == key:
        print("密钥正确,成功进入系统......")
        login(getua())
    else:
        print("您的密钥有误,请联系作者获取正确密钥")
        time.sleep(3)
        sys.exit()
    while True:
        print('---------------------主功能菜单------------------------')
        print('1.进行课程报名')
        print('2.进行已报名课程学习')
        print('3.联系作者')
        print('0.退出软件')
        index = int(input('请选择您要使用的功能:'))
        if index == 1:
            enrollable()
        elif index == 2:
            get_lesson()
        elif index == 3:
            contact_wechat()
            contact_qq()
        elif index == 0:
            a = input('您是否确认退出? Y/N')
            if a == 'Y' or a == 'y':
                break
            else:
                print("您已取消,已返回主菜单")


def contact_wechat():
    print("微信:LOGO.MY1314")


def contact_qq():
    print("QQ:21194524\n邮箱:21194524@qq.com")


# 伪装请求头
def getua():
    url_ua = 'https://fake-useragent.herokuapp.com/browsers/0.1.11'
    print('正在伪装请求头User-Agent......')
    resp = requests.get(url_ua)
    dict_ua = resp.json()
    i = random.randint(0, 30)
    ua = dict_ua['browsers']['chrome'][i]
    return ua


# 获取登录信息
def login(ua):
    username = input('请输入您的用户名:')
    passwd = input('请输入您的密码:')
    print('伪装成功', ua)
    url_login = 'http://www.hebgb.gov.cn/portal/login_ajax.do'
    data = {
        "username": f"{username}",
        "passwd": f"{passwd}"
    }
    headers = {
        "Host": "www.hebgb.gov.cn",
        "Referer": "http://www.hebgb.gov.cn/",
        "User-Agent": f"{ua}"
    }
    # 登录请求
    a = session.post(url_login, data=data)
    if "错误" in a.text:
        print(a.text)
    millis = int(round(time.time() * 1000))
    url_getinfo = f'http://www.hebgb.gov.cn/portal/checkIsLogin.do?_={millis}'
    resp = session.get(url_getinfo)
    print('------------------------------------------------------')
    dict_info = resp.json()
    # 真实姓名
    realname = dict_info['realname']
    # 要求总学时
    yqzxs = dict_info['yqzxs']
    # 已完成学时
    ywczxs = dict_info['ywczxs']
    # 要求必修总学时
    yqbxxs = dict_info['yqbxxs']
    # 已完成必修总学时
    ywcbxxs = dict_info['ywcbxxs']
    print(f"欢迎您 {realname} 同志,\n"
          f"要求总学时为{yqzxs},已完成学时{ywczxs},\n"
          f"要求必修总学时为{yqbxxs},已完成必修总学时{ywcbxxs}")


# 获取可报名课程
def enrollable():
    def choose():
        nonlocal result_1
        index_chose = int(input('请输入您想要报名的课程序号:')) - 1
        cid_choose = result_1[index_chose][0]
        url_chose = 'http://www.hebgb.gov.cn/student/class_register.do'
        params_choose = {
            "cid": f"{cid_choose}",
            "type": "1",
            "url": "learn"
        }
        resp_chose = session.get(url_chose, params=params_choose)
        regex_2 = re.compile(r'alert(.*?);', re.S)
        alert = regex_2.findall(resp_chose.text)
        print("报名状态为:", alert[0])

    global table
    url_enrollable = 'http://www.hebgb.gov.cn/student/class_notMyClassList.do?type=1&menu=myclass'
    resp_enrollable = session.get(url_enrollable)
    regex_1 = re.compile(r'"/portal/class_detail.do.*?&cid=(.*?)" title="(.*?)>', re.S)
    result_1 = regex_1.findall(resp_enrollable.text)
    print("成功获取到课程信息:")
    table = PrettyTable(['序号', 'cid', 'title'])
    for i in range(len(result_1)):
        table.add_row([i + 1, result_1[i][0], result_1[i][1]])
    if len(result_1) == 0:
        print(table)
        print("暂无可报名课程!")
    else:
        print(table)
        choose()


# 获取可以学习的课程
def get_lesson():
    # 学习任务
    def job(id_course, rate, study_course, sumtime):
        headers = {
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
            "Accept-Encoding": "gzip,deflate",
            "Accept-Language": "zh-CN, zh;q=0.9",
            "Connection": "keep-alive",
            "Content-Length": "0",
            "Host": "www.hebgb.gov.cn",
            "Origin": "http://www.hebgb.gov.cn",
            "Referer": f"http://www.hebgb.gov.cn/portal/study_play.do?id={id_course}"
        }
        url = f'http://www.hebgb.gov.cn/portal/study_play.do?id={id_course}'
        session.get(url, headers=headers)
        number = int(int(sumtime) * 60 / rate)
        print("预计本节所需时长为", f"{int(int(sumtime) * 60 / rate)+1}秒")
        url_learn = f'http://www.hebgb.gov.cn/portal/seekNew.do'
        global count
        for k in trange(number + 1, ncols=100, desc=f'本章节学习进度'):
            time.sleep(1)
            time_stamp = time.time()
            time_array = time.localtime(time_stamp)  # 格式化时间戳为本地时间
            # 本地格式化时间
            format_time = time.strftime("%Y-%m-%d %H:%M:%S", time_array)
            res01 = {"lesson_location": f'{k * rate}', "session_time": 29, "last_learn_time": f"{format_time}"}
            dict_0 = {'res01': res01, 'last_study_sco': "res01"}
            data = {
                "id": f"{id_course}",
                "serializeSco": f'{dict_0}',
                "duration": f"{rate}",
                "study_course": f"{study_course}"
            }
            session.post(url_learn, data=data)
        print(f"章节:ID{study_course}  学习完成......")
        print('------------------------------------------------------')

    # 选择学习的课程
    def chose_lesson():
        index_lesson = int(input('请选择您需要学习的课程序号:'))
        lesson_cid = result_3[index_lesson - 1][0]
        lesson_name = result_3[index_lesson - 1][1]
        print('您选择的课程cid为:', lesson_cid)
        print('您选择的课程名称为:', lesson_name)
        return lesson_cid

    # 进行学习任务
    def get_chapter(lesson_cid):
        global count
        url_chapter = f'http://www.hebgb.gov.cn/student/class_detail_course.do?cid={lesson_cid}&elective_type=1&menu=myclass&tab_index=0'
        resp_chapter = session.get(url_chapter)
        regex_4 = re.compile(r'courseId=(.*?)".*?</i>(.*?) 分钟.*?\((.*?)\)"', re.S)
        result_4 = regex_4.findall(resp_chapter.text)
        if len(result_4) == 0:
            print("本课程已经过期,无法进行学习!")
        else:
            rate = int(input("请输入您需要的学习倍率(数字):"))
            for ids in result_4:
                id_course = ids[2]
                study_course = ids[0]
                sumtime = ids[1]
                print(f"正在学习第{count}节,总时长为{sumtime}分钟,")
                job(id_course, rate, study_course, sumtime)
                count += 1
            print('学习完成,已自动返回主菜单......')

    url_lesson = 'http://www.hebgb.gov.cn/student/class_myClassList.do?type=1&menu=myclass'
    resp_lesson = session.get(url_lesson)
    regex_3 = re.compile('.*?cid=(.*?)&elective_type=1&menu=myclass&tab_index=0" title="(.*?)">')
    result_3 = regex_3.findall(resp_lesson.text)
    table_0 = PrettyTable(('序号', 'cid', 'title'))
    for j in range(len(result_3)):
        table_0.add_row((j + 1, result_3[j][0], result_3[j][1]))
    print(table_0)
    if len(result_3) == 0:
        print("未查询到可学习课程,请进行报名!")
    else:
        get_chapter(chose_lesson())


if __name__ == '__main__':
    count = 1
    session = requests.Session()
    try:
        main()
    except Exception as e:
        print("错误信息:",e)
        print("请检查您输入的内容是否合法!")
        print("若非用户因素,将报错截图发送至作者VX,供作者优化程序!")
        time.sleep(3)

使用页面截图:

 

 

 使用说明:

软件密钥为软件使用时显示的日期xxxx-xx-xx全字段的32位小写md5加密,输入成功之后会自动跳转系统,然后进行课程操作即可,可能会有些许兼容,本脚本为9月份进行末次更新,刚才在测试中可能会出现部分乱码,但是总体上不影响功能选项的使用。

 软件下载链接:

Cyber.exe - 蓝奏云文件大小:39.9 M|https://wwd.lanzoub.com/idfYb0d1gorc

评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MA21194524

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值