本文将介绍如何使用Python根据学号查看成绩的方法。
一、获取学生成绩的接口
首先,需要获得学生成绩的接口。由于不同学校、不同系统的接口不同,这里以某高校教务系统为例,假设该高校教务系统提供的成绩查询接口为:
http://jwgl.xxx.edu.cn/cjcx.do?xh={学号}&fajhh={学年学期代码}
其中,{学号}为学生的学号,{学年学期代码}为教务系统中设定的学年学期代码,例如2019-2020学年第一学期的代码为19301。
二、使用Python进行模拟登录
在访问学生成绩查询接口之前,需要先进行模拟登录操作获取cookie。可以使用Python中的requests库进行登录,并获取登录成功后返回的cookie。
import requests
# 模拟登录
url = 'http://jwgl.xxx.edu.cn/login.do'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
}
data = {
'xh': '学号',
'mm': '密码'
}
session = requests.session()
response = session.post(url, headers=headers, data=data, allow_redirects=False)
# 获取cookie
cookie = ''
for c in response.cookies:
cookie += c.name + '=' + c.value + ';'
三、根据学号查询成绩
通过模拟登录获取到cookie之后,即可通过访问成绩查询接口,传入对应的学号和学期代码,来查询学生成绩。
import requests
# 查询学生成绩
url = 'http://jwgl.xxx.edu.cn/cjcx.do?xh=学号&fajhh=学年学期代码'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
'Cookie': 'cookie'
}
session = requests.session()
response = session.get(url, headers=headers)
# 解析成绩信息
score_list = []
if response.status_code == 200:
soup = BeautifulSoup(response.content, 'html.parser')
table = soup.find('table', {'class': 'datagridstyle'})
if table:
tr_list = table.find_all('tr')
for tr in tr_list[1:]:
td_list = tr.find_all('td')
score_list.append({
'course_name': td_list[3].text.strip(),
'course_type': td_list[4].text.strip(),
'credit': td_list[6].text.strip(),
'score': td_list[7].text.strip()
})
四、展示查询结果
最后,可以将查询到的成绩信息展示在终端或者输出到文本文件中,方便查看。
# 输出成绩信息到终端
for score in score_list:
print(score['course_name'], score['course_type'], score['credit'], score['score'])
# 输出成绩信息到文件
with open('score.txt', 'w') as f:
for score in score_list:
f.write(score['course_name'] + ',' + score['course_type'] + ',' + score['credit'] + ',' + score['score'] + 'n')
五、总结
本文介绍了使用Python进行根据学号查看成绩的方法。需要获取查询接口、模拟登录、访问接口、解析数据等步骤。希望对大家有所帮助。