zoukankan      html  css  js  c++  java
  • 使用Python计算研究生学分绩(绩点)

    最近看了CSDN上一个专栏《Python爬虫入门教程》,其中最后一篇作者写了个例子,用爬虫计算山东大学绩点,顿时想到前一阵子搞测评的时候还得拿计算器一点点算自己的平均学分绩,也想写一个自己学校的计算学分绩的爬虫。(吐槽:这么简单的功能学校网站居然不实现以下!)

    具体过程专栏作者写得很清楚,详见 [Python]网络爬虫(十):一个爬虫的诞生全过程(以山东大学绩点运算为例)。作者使用了Firefox的HTTPFox插件来进行POST和GET消息分析,并通过查看源代码来查找到模拟登陆和查询成绩时的URL(其实这里使用Firefox的FireBug插件更简单)。使用这两个插件使我这个对网站编程一窍不通的人都能搞出个模拟登陆来。

    根据那篇博文,整个过程分为以下几步:

    1. 打开教务系统网站,查看登陆时发送了哪些信息,分析POST和GET信息,并在模拟登陆时使用;
    2. 进入网站后,查看如何与网站交互,同步骤一,分析这些信息,在模拟查询时使用;
    3. 使用爬虫模拟登陆和查询,得到成绩页面的html代码;
    4. 使用正则表达式提取得到的html代码中的所有成绩信息;
    5. 通过提取到的成绩信息计算平均学分绩。

    具体操作细节可以参考上面那篇博文。此处不再赘述。

    这里写一下我遇到的问题。上述博文中,作者登陆成绩查询系统后,直接找到成绩查询页面的URL就可以得到成绩页面的html代码,而在我们学校的教务系统中我却怎么也找不到该URL。经过N多次实验发现,我们学校查询的时候也会发送一个特定格式的POST信息,然后才会返回成绩页面,也就是说得再次模拟发送一次浏览成绩信息。感觉是由于自己对网站相关知识不了解,认为只要模仿就能取得结果,殊不知这里查询方式的不同,浪费了不少时间。

    得到网页信息后,就需要写正则表达式来提取成绩信息。关于Python的正则表达式详见:[Python]网络爬虫(七):Python中的正则表达式教程。对于正则表达式不熟的人推荐一个在线测试的网站:Regex Tester ,这个网站可以测试写的正则表达式能不能正确匹配要提取的信息。

    附上源代码:

     1 # -*- coding: utf-8 -*-
     2 # author: Kill Console
     3 # 功能:计算西工大研究生本学期成绩学分绩
     4 
     5 import urllib
     6 import urllib2
     7 import cookielib
     8 import re
     9 
    10 REQUIRED = '<font color=red >xe5xadxa6xe4xbdx8dxe5xbfx85xe4xbfxaexe8xafxbe</font>'       # 必修
    11 ELECTIVE = 'xe5xadxa6xe4xbdx8dxe9x80x89xe4xbfxaexe8xafxbe'                               # 选修
    12 
    13 class NPUSpider:
    14     def __init__(self, stuid, pwd):
    15         self.login_url = 'http://222.24.211.70/grsadmin/servlet/studentLogin'               # 登陆url
    16         self.query_url = 'http://222.24.211.70/grsadmin/servlet/studentMain'                # 成绩查询url
    17         self.cookie_jar = cookielib.CookieJar()                                             # 初始化一个CookieJar来处理Cookie的信息
    18         self.post_data_login = urllib.urlencode({'TYPE':'AUTH', 'glhj':'', 'USER':stuid, 'PASSWORD':pwd})          # POST登录数据
    19         self.post_data_query = urllib.urlencode({'MAIN_TYPE':'3', 'MAIN_SUB_ACTION':'浏览成绩', 'MAIN_NEXT_ACTION':'LL', 'MAIN_PURPOSE':'/jsp/student_JhBrow.jsp'})     # POST查询数据
    20         self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookie_jar))
    21         self.course_data = []       # 存储一门课的信息,包括课程号、课程名、学分、成绩等
    22         self.weights = []           # 存储学分
    23         self.scores = []            # 存储成绩
    24         self.GPA = 0.0
    25 
    26     def init_spider(self):
    27         req_login = urllib2.Request(url = self.login_url, data = self.post_data_login)      # 自定义一个登录请求
    28         result_login = self.opener.open(req_login)                                          # 访问登录页面
    29         req_query = urllib2.Request(url = self.query_url, data = self.post_data_query)      # 自定义一个查询请求
    30         result_query = self.opener.open(req_query)                                          # 访问成绩页面
    31         self.process_data(result_query.read().decode('gbk').encode('utf-8'))                # 由于存在中文,先解码再编码
    32         self.calculate_GPA()
    33 
    34     def process_data(self, res_page):
    35         self.course_data = re.findall(r'<TR>s+<TD width=60 class=style2><div.*?>(.*?)</div>.*?<div.*?>(.*?)</div>.*?<div.*?>s+(.*?)s+</div>.*?<div.*?>(.*?)</div>.*?<div.*?>(.*?)</div>.*?<div.*?>(.*?)</div>.*?<div.*?>(.*?)</div>.*?</TR>', res_page, re.S)
    36         for item in self.course_data:
    37             self.weights.append(item[4])
    38             self.scores.append(item[5])
    39             
    40     def calculate_GPA(self):
    41         sum_score = 0.0
    42         sum_weight = 0.0
    43         for i in range(len(self.course_data)):
    44             if self.course_data[i][2] == REQUIRED and self.scores[i].isdigit():             # 判断该科目是否是必修且是否有分数,若是则进行计算
    45                 sum_score += float(self.weights[i]) * float(self.scores[i])
    46                 sum_weight += float(self.weights[i])
    47         self.GPA = sum_score / sum_weight
    48 
    49     def print_GPA(self):  
    50         print u'课程代码		类型		学期		学分		成绩		得分日期		课程名称'
    51         print '-'*120
    52         for item in self.course_data:
    53             if item[2] == REQUIRED:
    54                 rqd = 'xe5xadxa6xe4xbdx8dxe5xbfx85xe4xbfxaexe8xafxbe'
    55                 print '%s		%s	%s		%s		%s		%s		%s' % (item[0], rqd, item[3], item[4], item[5], item[6], item[1])
    56             else:
    57                 print '%s		%s	%s		%s		%s		%s		%s' % (item[0], item[2], item[3], item[4], item[5], item[6], item[1])
    58         print 
    59         print 'The GPA is %.4f' % self.GPA
    60 
    61 
    62 def main():
    63     stuid = raw_input('student ID: ').strip()
    64     pwd = raw_input('pass word: ').strip()
    65 
    66     spider = NPUSpider(stuid, pwd)
    67     spider.init_spider()
    68     spider.print_GPA()
    69 
    70 if __name__ == '__main__':
    71     main()

    以下是一个西工大本科生学分绩计算脚本,由于测试时没有进行教学评估的查询不了,只能查询本学期成绩,所以计算的是本学期成绩学分绩(只计算必修):

     1 # -*- coding: utf-8 -*-
     2 # author: Kill Console
     3 # 功能:计算西工大本科生本学期成绩学分绩
     4 
     5 import urllib
     6 import urllib2
     7 import cookielib
     8 import re
     9 
    10 REQUIRED = 'xe5xbfx85xe4xbfxae'       # 必修
    11 ELECTIVE = 'xe4xbbxbbxe9x80x89'       # 选修
    12 
    13 class NPUSpider:
    14     def __init__(self, stuid, pwd):
    15         self.login_url = 'http://jw.nwpu.edu.cn/loginAction.do'             # 登陆url
    16         self.result_url = 'http://jw.nwpu.edu.cn/bxqcjcxAction.do'          # 本学期成绩查询url
    17         self.cookie_jar = cookielib.CookieJar()                             # 初始化一个CookieJar来处理Cookie的信息
    18         self.post_data = urllib.urlencode({'zjh':stuid, 'mm':pwd})          # POST的数据
    19         self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookie_jar))
    20         self.course_data = []       # 存储一门课的信息,包括课程号、课程名、学分、成绩等
    21         self.weights = []           # 存储学分
    22         self.scores = []            # 存储成绩
    23         self.GPA = 0.0
    24 
    25     def init_spider(self):
    26         req = urllib2.Request(url = self.login_url, data = self.post_data)      # 自定义一个请求
    27         result = self.opener.open(req)                                          # 访问登录页面
    28         result = self.opener.open(self.result_url)                              # 访问成绩页面
    29         self.process_data(result.read().decode('gbk').encode('utf-8'))
    30         self.calculate_GPA()
    31 
    32     def process_data(self, res_page):
    33         self.course_data = re.findall(r'<tr class=.*?<td.*?>s+(.*?)s+</td>.*?<td.*?>s+(.*?)s+</td>.*?<td.*?>s+(.*?)s+</td>.*?<td.*?>s+(.*?)s+</td>.*?<td.*?>s+(.*?)s+</td>.*?<td.*?>s+(.*?)s+</td>.*?<td.*?>s+(.*?)s+</td>.*?</tr>', res_page, re.S)
    34         for item in self.course_data:
    35             self.weights.append(item[4])
    36             self.scores.append(item[6])
    37             
    38     def calculate_GPA(self):
    39         sum_score = 0.0
    40         sum_weight = 0.0
    41         for i in range(len(self.course_data)):
    42             if self.course_data[i][5] == REQUIRED and self.scores[i].isdigit():
    43                 sum_score += float(self.weights[i]) * float(self.scores[i])
    44                 sum_weight += float(self.weights[i])
    45         self.GPA = sum_score / sum_weight
    46 
    47     def print_GPA(self):
    48         print 'The GPA is %.4f' % self.GPA
    49 
    50 def main():
    51     stuid = raw_input('student ID: ').strip()
    52     pwd = raw_input('pass word: ').strip()
    53 
    54     spider = NPUSpider(stuid, pwd)
    55     spider.init_spider()
    56     spider.print_GPA()
    57 
    58 if __name__ == '__main__':
    59     main()
    View Code
  • 相关阅读:
    centos 7 -- Disk Requirements: At least 134MB more space needed on the / filesystem.
    DNS Server Centos 7
    生成report由Eamil定時寄出
    WRT 版本说明
    cisco linksys ea3500 刷机 openwrt
    [QNAP crontab 定時執行程式
    实例 编辑 .bashrc(不断更新)
    tar命令
    ls -l 显示年份
    git 丢弃本地代码时遇到的问题
  • 原文地址:https://www.cnblogs.com/dukeleo/p/3410193.html
Copyright © 2011-2022 走看看