Python實現新版正方教務系統爬蟲(二)

前言

哎對不起 我可能是silly boy 我想在學校裏把去年的坑填了 但是發現新版的教務系統代碼沒傳到git上 我現在就成了個對着空ide發呆的憨憨(代碼在家裏啦 所以填坑就再過會吧

那就稍微閒聊一下吧 打算填坑前逛了一下csdn上面有關新版正方教務系統的帖子 我去年留下的rsa加密的坑其實都被填掉了 也有用flask框架完善整個項目的
其實挺好的 寫博客就是爲了幫助更多的志同道合之人在這條路上進步 告訴你們我是怎麼走到這裏的 走了多少的坑
爲中華崛起而奮鬥~~

正文哈

國慶之後終於是想起來要把代碼拷走這回事情,現在基本是填完了啦。
給剛學習爬蟲的小白們做了封裝 希望能夠幫助你們理解

新版的方正教務系統唯一的難點也就是在登陸加密的地方了,這裏感謝@qq_14926447 使用了他代碼中的輪子 於是我也能快樂的跑起來啦~

實現的原理貼在上個教程裏面了 就直接上乾貨吧

github項目鏈接:https://github.com/welsonsxc/NewZFScoreSpider

講解一下

整個流程我封裝成一個類了,方便後續api或者多線程調用
wechat_robot文件夾裏是當時做測試公衆號用的 學校方面沒法申請下來經費就逐漸廢棄了 如果你們學校可以的話 不妨研究一下 填填坑

噥 知道你們最喜歡這個了 再次感謝@qq_14926447

    # 加密密碼
    def process_public(self):
        weibo_rsa_e = 65537
        message = str(self.password).encode()
        rsa_n = binascii.b2a_hex(binascii.a2b_base64(self.modules))
        key = rsa.PublicKey(int(rsa_n, 16), weibo_rsa_e)
        encropy_pwd = rsa.encrypt(message, key)
        self.password = binascii.b2a_base64(encropy_pwd)

我知道有人懶得點進github

# -*- coding: utf-8 -*-
import binascii
import requests
from bs4 import BeautifulSoup
import re
import time
import sys
import rsa


class Student:
    sessions = requests.Session()
    time = int(time.time())

    def __init__(self, name, password, login_url, key_url, grade_url):
        self.pub = None
        self.year = None
        self.term = None
        self.token = None
        self.header = None
        self.cookie = None
        self.modules = None
        self.request = None

        self.name = str(name).encode("utf8").decode("utf8")
        self.password = str(password).encode("utf8").decode("utf8")
        self.url = login_url
        self.KeyUrl = key_url
        self.gradeUrl = grade_url
        self.get_public_key()
        self.get_csrf_token()
        self.process_public()
        self.login()

    # 獲取公鑰密碼
    def get_public_key(self):
        result = self.sessions.get(self.KeyUrl + str(self.time)).json()
        self.modules = result["modulus"]
        # 說實話 這也太那啥了 這居然是沒用的 怪不得去年栽在這裏
        # self.exponent = result["exponent"]

    # 獲取CsrfToken
    def get_csrf_token(self):
        r = self.sessions.get(self.url + str(self.time))
        r.encoding = r.apparent_encoding
        soup = BeautifulSoup(r.text, 'html.parser')
        self.token = soup.find('input', attrs={'id': 'csrftoken'}).attrs['value']

    # 加密密碼
    def process_public(self):
        weibo_rsa_e = 65537
        message = str(self.password).encode()
        rsa_n = binascii.b2a_hex(binascii.a2b_base64(self.modules))
        key = rsa.PublicKey(int(rsa_n, 16), weibo_rsa_e)
        encropy_pwd = rsa.encrypt(message, key)
        self.password = binascii.b2a_base64(encropy_pwd)

    def login(self):
        try:
            self.header = {
                'Accept': 'text/html, */*; q=0.01',
                'Accept-Encoding': 'gzip, deflate',
                'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:58.0) Gecko/20100101 Firefox/58.0',
                'Connection': 'keep-alive',
                'Referer': self.url + str(self.time),
                'Upgrade-Insecure-Requests': '1',
            }
            data = {
                'csrftoken': self.token,
                'mm': self.password,
                'mm': self.password,
                'yhm': self.name
            }
            self.request = self.sessions.post(self.url, headers=self.header, data=data)
            self.cookie = self.request.request.headers['cookie']
            key_word = r'用戶名或密碼不正確'
            if re.findall(key_word, self.request.text):
                print('用戶名或密碼錯誤,請查驗..')
                sys.exit()
            else:
                print("登陸成功")
        except Exception as e:
            print(str(e))
            sys.exit()

    def post_grade_data(self):
        try:
            data = {'_search': 'false',
                    'nd': int(time.time()),
                    'queryModel.currentPage': '1',
                    'queryModel.showCount': '15',
                    'queryModel.sortName': '',
                    'queryModel.sortOrder': 'asc',
                    'time': '0',
                    'xnm': self.year,
                    'xqm': self.term
                    }
            self.request = self.sessions.post(self.gradeUrl, data=data, headers=self.header).json()
        except Exception as e:
            print(str(e))
            sys.exit()

    def welcome(self):
        try:
            # 姓名
            name = self.request['items'][0]['xm']
            # 學歷
            sch_stu = self.request['items'][0]['xslb']
            # 學院
            institute = self.request['items'][0]['jgmc']
            # 班級
            stu_class = self.request['items'][0]['bj']
            print('姓名:{}\t學歷:{}\t\t學院:{}\t班級:{}'.format(name, sch_stu, institute, stu_class))
        except Exception as e:
            print(str(e))

    def print_grades(self):
        try:
            plt = '{0:<20}{1:<5}{2:<5}{3:<5}'
            print(plt.format('課程', '成績', '績點', '教師'))
            for i in self.request['items']:
                print(plt.format(i['kcmc'], i['bfzcj'], i['jd'], i['jsxm']))
        except Exception as e:
            print("[Error]" + str(e))


if __name__ == '__main__':
    # 輸入學號密碼
    # stu_name = input('請輸入學號:').strip()
    stu_name = "你的學號"
    # stu_password = getpass.getpass('請輸入密碼(密碼不回顯,輸入完回車即可):') .strip()
    stu_password = "你的密碼"

    # 教務系統登錄路徑
    url = "http://你的學校域名或者ip地址/jwglxt/xtgl/login_slogin.html?language=zh_CN&_t="
    # 請求PublicKey的URL
    key_url = "http://你的學校域名或者ip地址/jwglxt/xtgl/login_getPublicKey.html?time="
    # 獲取成績路徑
    grade_url = "http://你的學校域名或者ip地址/jwglxt/cjcx/cjcx_cxDgXscj.html?doType=query&gnmkdm=N305005"

    # 登陸~
    temp = Student(stu_name, stu_password, url, key_url, grade_url)
    # 設定學年
    temp.year = "2018"
    # 第一學期爲3 第二學期爲12
    temp.term = "3"
    # 選擇成績查詢
    temp.post_grade_data()
    # 輸出個人信息
    temp.welcome()
    # 輸出成績信息
    temp.print_grades()

運行結果

在這裏插入圖片描述

感覺沒啥好講的 都是乾貨 git大學一定要學會呀 公司裏都在用~
如果幫助到你了 煩請star!
最後留個工作郵箱 [email protected]

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章