1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
| ''' 大连大学成绩查询助手V1.7.190216 Code By ZC Liang 2018.6.6 Completed on 2019.2.15 '''
import getpass import http.cookiejar import os import pickle import platform import random import re import smtplib import subprocess import sys import time import urllib.parse import urllib.request from email.mime.text import MIMEText from email.utils import formataddr
import bs4 import numpy as np import pandas as pd import prettytable as pt import pymysql import requests from aip import AipOcr from bs4 import BeautifulSoup from PIL import Image from prettytable import PrettyTable from requests import ReadTimeout from requests import ConnectionError
my_sender = '发件人邮箱账号' my_pass = '发件人邮箱密码'
email_send_to = ''
DstDir = os.getcwd() searchCount = 0 count = 0 scorenum = 0 score = [] scorenp = np.array(score) makeup_course_num = 0 makeup_course_flag = -1 courseList = [] required_course_num = 0
cookie = http.cookiejar.CookieJar() opener = urllib.request.build_opener( urllib.request.HTTPCookieProcessor(cookie))
final_url = "" final_url_head = "" url_head = "202.199.155." + str(random.randint(33, 37))
ddlxn = "" ddlxq = ""
""" 你的 APPID AK SK """ APP_ID = '你的 APP_ID' API_KEY = '你的 API_KEY' SECRET_KEY = '你的 SECRET_KEY'
client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
""" 读取图片 """ def get_file_content(filePath): with open(filePath, 'rb') as fp: return fp.read()
def getOpeningSystem(): return platform.system()
def getOpeningSystem(): return platform.system()
def isConnected(): try: response = requests.get('http://' + url_head, timeout=1) if response.status_code == 200: return True else: print('网络检测错误status_code: ' + response.status_code, 'http://' + url_head) return False except (ConnectionError, ReadTimeout): print('无网络连接。')
def check_for_redirects(url): r = requests.head(url) if r.ok: return r.headers['location'] else: return '[no redirect]'
def image_util(img): new_im = img.convert("RGB") new_im.save('' + DstDir + '\\ScoreHelper\\CheckCode1.jpg')
arr = np.array(Image.open('' + DstDir + '\\ScoreHelper\\CheckCode1.jpg').convert("L"))
b = 255 - arr im = Image.fromarray(b.astype('uint8'))
im.save('' + DstDir + '\\ScoreHelper\\CheckCode2.jpg')
def code_recognition(): try: result = client.basicAccurate(get_file_content('' + DstDir + '\\ScoreHelper\\CheckCode2.jpg')) word = result.get('words_result') res = "" if len(word): res = re.findall('[a-zA-Z0-9]+', word[0].get('words'))[0] elif len(res) > 4: res = res[0:4] return res except Exception as e: print(e)
def login(): params = { 'txtUserName': sid, 'Textbox1': '', 'Textbox2': spwd, 'RadioButtonList1': '学生', 'Button1': '', 'lbLanguage': '', 'hidPdrs': '', 'hidsc': '', }
res = opener.open(final_url_head + '/checkcode.aspx').read() with open('' + DstDir + '\\ScoreHelper\\CheckCode.jpg', 'wb') as file: file.write(res) img = Image.open('' + DstDir + '\\ScoreHelper\\CheckCode.jpg')
image_util(img)
print('验证码识别结果:' + code_recognition()) vcode = code_recognition()
params['txtSecretCode'] = vcode
response = urllib.request.urlopen('http://' + url_head + '/') html = response.read().decode('gb2312') viewstate = re.search( '<input type="hidden" name="__VIEWSTATE" value="(.+?)"', html) params['__VIEWSTATE'] = viewstate.group(1) loginurl = final_url print("\n本次登录所用网址为:" + loginurl + "\n") data = urllib.parse.urlencode(params).encode('gb2312') response = opener.open(loginurl, data) if response.geturl() == final_url: print('登陆失败,可能是姓名,学号,密码或验证码填写错误!') return False else: return True
def get_RequiredCourse_num(): global required_course_num
print("正在查询本学期必修课数目...") url = ''.join([ final_url_head + '/xsxkqk.aspx', '?xh=', sid, '&xm=', urllib.parse.quote(sname), '&gnmkdm=N121615', ]) params = { 'ddlxn': ddlxn, 'ddlxq': ddlxq, }
req = urllib.request.Request(url) req.add_header('Referer', final_url) req.add_header('Origin', 'http://' + url_head + '/') req.add_header( 'User-Agent', 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36') response = opener.open(req) html = response.read().decode('gb2312') viewstate = re.search( '<input type="hidden" name="__VIEWSTATE" value="(.+?)"', html) params['__VIEWSTATE'] = viewstate.group(1)
req = urllib.request.Request( url, urllib.parse.urlencode(params).encode('gb2312')) req.add_header('Referer', final_url) req.add_header('Origin', 'http://' + url_head + '/') response = opener.open(req) soup = BeautifulSoup(response.read().decode('gb2312'), 'html.parser') html = soup.find('table', class_='datelist')
flag = True counter = 0 for each in html: columnCounter = 0 column = []
if type(each) == bs4.element.NavigableString: pass else: for item in each.contents: if item != '\n': if counter > 0 and columnCounter == 3: courseList.append(str(item.contents[0]).strip()) columnCounter += 1 if flag: flag = False counter += 1
for each in courseList: if each == "必修课程": required_course_num += 1
def getScore(): global searchCount global scorenum global scorenp global ddlxn global ddlxq score = []
url = ''.join([ final_url_head + '/xscjcx_dq.aspx', '?xh=', sid, '&xm=', urllib.parse.quote(sname), '&gnmkdm=N121605', ]) params = { 'ddlxn': ddlxn, 'ddlxq': ddlxq, 'btnCx': '查询', }
req = urllib.request.Request(url) req.add_header('Referer', final_url) req.add_header('Origin', 'http://' + url_head + '/') req.add_header( 'User-Agent', 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36') response = opener.open(req) html = response.read().decode('gb2312') viewstate = re.search( '<input type="hidden" name="__VIEWSTATE" value="(.+?)"', html) params['__VIEWSTATE'] = viewstate.group(1)
req = urllib.request.Request( url, urllib.parse.urlencode(params).encode('gb2312')) req.add_header('Referer', final_url) req.add_header('Origin', 'http://' + url_head + '/') response = opener.open(req) soup = BeautifulSoup(response.read().decode('gb2312'), 'html.parser') html = soup.find('table', class_='datelist')
print("执行第" + str(searchCount) + "次查询:") print('你的所有成绩如下:')
outColumn = [3, 4, 6, 7, 9, 11, 13] flag = True for each in html: columnCounter = 0 column = []
if type(each) == bs4.element.NavigableString: pass else: for item in each.contents: if item != '\n': if columnCounter in outColumn: column.append(str(item.contents[0]).strip()) columnCounter += 1 if flag: table = PrettyTable(column) flag = False else: table.add_row(column) score.extend([column]) searchCount += 1 scorenp = np.array(score)
print(table) print("分条统计:") scorenum = sendScore(table) print("成绩数目: " + str(scorenum) + "条")
def sendScore(table): global scorenum global count global email_send_to global scorenp for i in table: print(i.get_string()) count += 1
if count > scorenum: try: scorenum = count
msg = prettyScore()
msg['From'] = formataddr(["1115810371@qq.com", my_sender]) msg['To'] = formataddr([email_send_to, email_send_to])
if count == required_course_num: msg['Subject'] = "第" + str(count) + "次成绩推送加平均绩点" else: msg['Subject'] = "第" + str(count) + "次成绩推送"
server = smtplib.SMTP_SSL("smtp.qq.com", 465) server.login(my_sender, my_pass) server.sendmail(my_sender, [email_send_to, ], msg.as_string()) server.quit() print("发送成功,请注意在此邮箱查收:" + email_send_to) except Exception as e: print(e) print("发送失败!") count = 0 if scorenum != required_course_num: print("程序休息中...(按'Ctrl C'结束)") time.sleep(1200) return scorenum
def prettyScore(): global scorenp try: msg = MIMEText(str(htmlText(scorenum)), "html", "gb2312") except Exception as e: print(e) return msg
def htmlText(scorenum): global required_course_num
html = """
<table color="CCCC33" width="800" border="1" cellspacing="0" cellpadding="5" text-align="center">
<tr>
<td>课程名称</td>
<td>课程性质</td>
<td>学分</td>
<td>平时成绩</td>
<td>期末成绩</td>
<td>成绩</td>
</tr>
""" + addtrs(scorenum) + """ </table> """
if scorenum == required_course_num: html += """ <br/> <div class='gpa_text' style='font-size: 25px;font-style: italic;'>-->平均绩点:%s <--</div> """ % (getGPA()) + """ <br/> <div class='end_words' style='font-size: 20px;'>本学期考试成绩查询完成!</div> """ return html
def addtrs(scorenum): global scorenp i = 1 array = [] while i <= scorenum: trs = ''' <tr>
<td>%s </td>
<td>%s </td>
<td>%s </td>
<td>%s </td>
<td>%s </td>
''' % (scorenp[i][0], scorenp[i][1], scorenp[i][2], scorenp[i][3], scorenp[i][4]) if (scorenp[i][5].isalpha() and scorenp[i][5] == "A") or (scorenp[i][5].isdigit() and int(scorenp[i][5]) >= 90): trs += '<td style="color:springgreen;">'
elif (scorenp[i][5].isalpha() and scorenp[i][5] == "F") or ( scorenp[i][5].isdigit() and int(scorenp[i][5]) < 60): trs += '<td style="color:red;">'
else: trs += '<td>'
trs += ''' %s </td>
</tr> ''' % (scorenp[i][5]) array.append(trs) i += 1 s = "" for x in array: s += str(x) return s
def getGPA(): global scorenp global scorenum global makeup_course_num global makeup_course_flag
sc = [] GPAlist = [] i = 1 j = 0 coursenum = 0
while i <= scorenum: if scorenp[i][1] != "必修课程" or scorenp[i][6] == "是": makeup_course_num += 1 i += 1 continue else: if scorenp[i][5].isalpha() and scorenp[i][5] != "F": sc.append(745 - 10 * ord(scorenp[i][5])) elif scorenp[i][5] == "F": sc.append(0) else: sc.append(int(scorenp[i][5]))
if int(sc[j]) < 60: GPAlist.append(0) else: GPAlist.append((int(sc[j]) - 50) / 10 * float(scorenp[i][2])) i += 1 j += 1 coursenum += 1
i = 1 j = 0 sum = 0 scoresum = 0
while i <= scorenum: if scorenp[i][1] != "必修课程" or scorenp[i][6] == "是": i += 1 continue sum += GPAlist[j] scoresum += float(scorenp[i][2]) j += 1 i += 1 GPA = sum / scoresum print("平均绩点:" + str(GPA)) return GPA
def setSemester(): global ddlxn global ddlxq
try: localtime = time.localtime(time.time())
if (int((localtime.tm_mon) >= 9 and int(localtime.tm_mon) <= 12) or ( int(localtime.tm_mon) >= 1 and int(localtime.tm_mon) <= 2)): if (int(localtime.tm_mon) >= 1 and int(localtime.tm_mon) <= 2): ddlxn = str(localtime.tm_year - 1) + '-' + str(int(localtime.tm_year)) else: ddlxn = str(localtime.tm_year) + '-' + str(int(localtime.tm_year) + 1) ddlxq = '1' else: ddlxn = str(int(localtime.tm_year) - 1) + '-' + str(localtime.tm_year) ddlxq = '2'
except Exception as e: print(e)
if __name__ == '__main__': setSemester()
try: searchCount = 1 print('欢迎使用大连大学成绩查询助手!') print('正在检查网络...') if isConnected(): with open(r'' + DstDir + '\\ScoreHelper\\uinfo.bin', 'rb') as file: udick = pickle.load(file) sname = udick['sname'] sid = udick['sid'] spwd = udick['spwd'] email_send_to = udick['email_send_to']
final_url = 'http://' + url_head + \ check_for_redirects('http://' + url_head + '/default2.aspx') final_url_head = final_url[0:48]
loginCount = 0 while not login(): if loginCount > 3: url_head = "202.199.155." + str(random.randint(33, 37)) final_url = 'http://' + url_head + \ check_for_redirects('http://' + url_head + '/default2.aspx') final_url_head = final_url[0:48] loginCount = 0 loginCount += 1 print("正在等待重试...") time.sleep(3) continue
get_RequiredCourse_num() getScore() counter = 0 while scorenum <= required_course_num: counter += 1 if scorenum == required_course_num: print("本学期成绩查询完成!") break if counter > 0: getScore() except FileNotFoundError: os.mkdir(r'' + DstDir + '\\ScoreHelper') print('这是你第一次使用,请按提示输入信息,以后可不必再次输入~') sid = input('请输入学号:') sname = input('请输入姓名:') spwd = input('请输入密码:') email_send_to = input('请输入要将成绩发送到的邮箱地址:') udick = {'sname': sname, 'sid': sid, 'spwd': spwd, 'email_send_to': email_send_to} file = open(r'' + DstDir + '\\ScoreHelper\\uinfo.bin', 'wb') pickle.dump(udick, file) file.close() final_url = 'http://' + url_head + \ check_for_redirects('http://' + url_head + '/default2.aspx') final_url_head = final_url[0:48]
while not login(): sname = input('请输入姓名:') sid = input('请输入学号:') spwd = input('请输入密码:') email_send_to = input('请输入要将成绩发送到的邮箱地址:') udick = {'sname': sname, 'sid': sid, 'spwd': spwd, 'email_send_to': email_send_to} file = open(r'' + DstDir + '\\ScoreHelper\\uinfo.bin', 'wb') pickle.dump(udick, file) file.close() final_url = 'http://' + url_head + \ check_for_redirects('http://' + url_head + '/default2.aspx') final_url_head = final_url[0:48] get_RequiredCourse_num() getScore() counter = 0 while scorenum <= required_course_num: counter += 1 if scorenum == required_course_num: print("本学期成绩查询完成!") break if counter > 0: getScore() print(scorenum)
except subprocess.CalledProcessError: print("网络连接不正常!请检查网络!") except Exception as e: print(e) print("失败!可能是你没有完成教学评价!没有完成教学评价则无法查看成绩!或用户中途取消或网络故障。") finally: print("程序将在3秒后退出...") time.sleep(3)
|