forked from openschoolcn/zfn_api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzfn_api.py
1516 lines (1460 loc) · 62.5 KB
/
zfn_api.py
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
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import base64
import binascii
import json
import re
import time
import traceback
import unicodedata
from urllib.parse import urljoin
import requests
import rsa
from pyquery import PyQuery as pq
from requests import exceptions
RASPIANIE = [
["8:00", "8:40"],
["8:45", "9:25"],
["9:30", "10:10"],
["10:30", "11:10"],
["11:15", "11:55"],
["14:30", "15:10"],
["15:15", "15:55"],
["16:05", "16:45"],
["16:50", "17:30"],
["18:40", "19:20"],
["19:25", "20:05"],
["20:10", "20:50"],
["20:55", "21:35"],
]
class Client:
raspisanie = []
ignore_type = []
def __init__(self, cookies={}, **kwargs):
# 基础配置
self.base_url = kwargs.get("base_url")
self.raspisanie = kwargs.get("raspisanie", RASPIANIE)
self.ignore_type = kwargs.get("ignore_type", [])
self.detail_category_type = kwargs.get("detail_category_type", [])
self.timeout = kwargs.get("timeout", 3)
Client.raspisanie = self.raspisanie
Client.ignore_type = self.ignore_type
self.key_url = urljoin(self.base_url, "/xtgl/login_getPublicKey.html")
self.login_url = urljoin(self.base_url, "/xtgl/login_slogin.html")
self.kaptcha_url = urljoin(self.base_url, "/kaptcha")
self.headers = requests.utils.default_headers()
self.headers["Referer"] = self.login_url
self.headers[
"User-Agent"
] = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"
self.headers[
"Accept"
] = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3"
self.sess = requests.Session()
self.sess.keep_alive = False
self.cookies = cookies
def login(self, sid, password):
"""登录教务系统"""
need_verify = False
try:
# 登录页
req_csrf = self.sess.get(
self.login_url, headers=self.headers, timeout=self.timeout
)
if req_csrf.status_code != 200:
return {"code": 2333, "msg": "教务系统挂了"}
# 获取csrf_token
doc = pq(req_csrf.text)
csrf_token = doc("#csrftoken").attr("value")
pre_cookies = self.sess.cookies.get_dict()
# 获取publicKey并加密密码
req_pubkey = self.sess.get(
self.key_url, headers=self.headers, timeout=self.timeout
).json()
modulus = req_pubkey["modulus"]
exponent = req_pubkey["exponent"]
if str(doc("input#yzm")) == "":
# 不需要验证码
encrypt_password = self.encrypt_password(password, modulus, exponent)
# 登录数据
login_data = {
"csrftoken": csrf_token,
"yhm": sid,
"mm": encrypt_password,
}
# 请求登录
req_login = self.sess.post(
self.login_url,
headers=self.headers,
data=login_data,
timeout=self.timeout,
)
doc = pq(req_login.text)
tips = doc("p#tips")
if str(tips) != "":
if "用户名或密码" in tips.text():
return {"code": 1002, "msg": "用户名或密码不正确"}
return {"code": 998, "msg": tips.text()}
self.cookies = self.sess.cookies.get_dict()
return {"code": 1000, "msg": "登录成功", "data": {"cookies": self.cookies}}
# 需要验证码,返回相关页面验证信息给用户,TODO: 增加更多验证方式
need_verify = True
req_kaptcha = self.sess.get(
self.kaptcha_url, headers=self.headers, timeout=self.timeout
)
kaptcha_pic = base64.b64encode(req_kaptcha.content).decode()
return {
"code": 1001,
"msg": "获取验证码成功",
"data": {
"sid": sid,
"csrf_token": csrf_token,
"cookies": pre_cookies,
"password": password,
"modulus": modulus,
"exponent": exponent,
"kaptcha_pic": kaptcha_pic,
"timestamp": time.time(),
},
}
except exceptions.Timeout:
msg = "获取验证码超时" if need_verify else "登录超时"
return {"code": 1003, "msg": msg}
except (
exceptions.RequestException,
json.decoder.JSONDecodeError,
AttributeError,
):
traceback.print_exc()
return {"code": 2333, "msg": "请重试,若多次失败可能是系统错误维护或需更新接口"}
except Exception as e:
traceback.print_exc()
msg = "获取验证码时未记录的错误" if need_verify else "登录时未记录的错误"
return {"code": 999, "msg": f"{msg}:{str(e)}"}
def login_with_kaptcha(
self, sid, csrf_token, cookies, password, modulus, exponent, kaptcha, **kwargs
):
"""需要验证码的登陆"""
try:
encrypt_password = self.encrypt_password(password, modulus, exponent)
login_data = {
"csrftoken": csrf_token,
"yhm": sid,
"mm": encrypt_password,
"yzm": kaptcha,
}
req_login = self.sess.post(
self.login_url,
headers=self.headers,
cookies=cookies,
data=login_data,
timeout=self.timeout,
)
if req_login.status_code != 200:
return {"code": 2333, "msg": "教务系统挂了"}
# 请求登录
doc = pq(req_login.text)
tips = doc("p#tips")
if str(tips) != "":
if "验证码" in tips.text():
return {"code": 1004, "msg": "验证码输入错误"}
if "用户名或密码" in tips.text():
return {"code": 1002, "msg": "用户名或密码不正确"}
return {"code": 998, "msg": tips.text()}
self.cookies = self.sess.cookies.get_dict()
# 不同学校系统兼容差异
if not self.cookies.get("route"):
route_cookies = {
"JSESSIONID": self.cookies["JSESSIONID"],
"route": cookies["route"],
}
self.cookies = route_cookies
else:
return {"code": 1000, "msg": "登录成功", "data": {"cookies": self.cookies}}
except exceptions.Timeout:
return {"code": 1003, "msg": "登录超时"}
except (
exceptions.RequestException,
json.decoder.JSONDecodeError,
AttributeError,
):
traceback.print_exc()
return {"code": 2333, "msg": "请重试,若多次失败可能是系统错误维护或需更新接口"}
except Exception as e:
traceback.print_exc()
return {"code": 999, "msg": "验证码登录时未记录的错误:" + str(e)}
def get_info(self):
"""获取个人信息"""
url = urljoin(self.base_url, "/xsxxxggl/xsxxwh_cxCkDgxsxx.html?gnmkdm=N100801")
try:
req_info = self.sess.get(
url,
headers=self.headers,
cookies=self.cookies,
timeout=self.timeout,
)
if req_info.status_code != 200:
return {"code": 2333, "msg": "教务系统挂了"}
doc = pq(req_info.text)
if doc("h5").text() == "用户登录":
return {"code": 1006, "msg": "未登录或已过期,请重新登录"}
info = req_info.json()
if info is None:
return self._get_info()
result = {
"sid": info.get("xh"),
"name": info.get("xm"),
"college_name": info.get("zsjg_id", info.get("jg_id")),
"major_name": info.get("zszyh_id", info.get("zyh_id")),
"class_name": info.get("bh_id", info.get("xjztdm")),
"status": info.get("xjztdm"),
"enrollment_date": info.get("rxrq"),
"candidate_number": info.get("ksh"),
"graduation_school": info.get("byzx"),
"domicile": info.get("jg"),
"postal_code": info.get("yzbm"),
"politics_status": info.get("zzmmm"),
"nationality": info.get("mzm"),
"education": info.get("pyccdm"),
"phone_number": info.get("sjhm"),
"parents_number": info.get("gddh"),
"email": info.get("dzyx"),
"birthday": info.get("csrq"),
"id_number": info.get("zjhm"),
}
return {"code": 1000, "msg": "获取个人信息成功", "data": result}
except exceptions.Timeout:
return {"code": 1003, "msg": "获取个人信息超时"}
except (
exceptions.RequestException,
json.decoder.JSONDecodeError,
AttributeError,
):
traceback.print_exc()
return {"code": 2333, "msg": "请重试,若多次失败可能是系统错误维护或需更新接口"}
except Exception as e:
traceback.print_exc()
return {"code": 999, "msg": "获取个人信息时未记录的错误:" + str(e)}
def _get_info(self):
"""获取个人信息"""
url = urljoin(self.base_url, "/xsxxxggl/xsgrxxwh_cxXsgrxx.html?gnmkdm=N100801")
try:
req_info = self.sess.get(
url, headers=self.headers, cookies=self.cookies, timeout=self.timeout
)
if req_info.status_code != 200:
return {"code": 2333, "msg": "教务系统挂了"}
doc = pq(req_info.text)
if doc("h5").text() == "用户登录":
return {"code": 1006, "msg": "未登录或已过期,请重新登录"}
pending_result = {}
# 学生基本信息
for ul_item in doc.find("div.col-sm-6").items():
content = pq(ul_item).find('div.form-group')
# key = re.findall(r'^[\u4E00-\u9FA5A-Za-z0-9]+', pq(content).find('label.col-sm-4.control-label').text())[0]
key = pq(content).find('label.col-sm-4.control-label').text()
value = pq(content).find('div.col-sm-8 p.form-control-static').text()
# 到这一步,解析到的数据基本就是一个键值对形式的html数据了,比如"[学号:]:123456"
pending_result[key] = value
# 学生学籍信息,其他信息,联系方式
for ul_item in doc.find("div.col-sm-4").items():
content = pq(ul_item).find('div.form-group')
key = pq(content).find('label.col-sm-4.control-label').text()
value = pq(content).find('div.col-sm-8 p.form-control-static').text()
# 到这一步,解析到的数据基本就是一个键值对形式的html数据了,比如"[学号:]:123456"
pending_result[key] = value
if pending_result.get("学号:") == '':
return {"code": 1014,
"msg": "当前学年学期无学生时盒数据,您可能已经毕业了。\n\n如果是专升本同学,请使用专升本后的新学号登录~"}
result = {
"sid": pending_result["学号:"],
"name": pending_result["姓名:"],
# "birthday": "无" if pending_result.get("出生日期:") == '' else pending_result["出生日期:"],
# "id_number": "无" if pending_result.get("证件号码:") == '' else pending_result["证件号码:"],
# "candidate_number": "无" if pending_result.get("考生号:") == '' else pending_result["考生号:"],
# "status": "无" if pending_result.get("学籍状态:") == '' else pending_result["学籍状态:"],
# "entry_date": "无" if pending_result.get("入学日期:") == '' else pending_result["入学日期:"],
# "graduation_school": "无" if pending_result.get("毕业中学:") == '' else pending_result["毕业中学:"],
"domicile": "无" if pending_result.get("籍贯:") == '' else pending_result["籍贯:"],
"phone_number": "无" if pending_result.get("手机号码:") == '' else pending_result["手机号码:"],
"parents_number": "无",
"email": "无" if pending_result.get("电子邮箱:") == '' else pending_result["电子邮箱:"],
"political_status": "无" if pending_result.get("政治面貌:") == '' else pending_result["政治面貌:"],
"national": "无" if pending_result.get("民族:") == '' else pending_result["民族:"],
# "education": "无" if pending_result.get("培养层次:") == '' else pending_result["培养层次:"],
# "postal_code": "无" if pending_result.get("邮政编码:") == '' else pending_result["邮政编码:"],
# "grade": int(pending_result["学号:"][0:4]),
}
if pending_result.get("学院名称:") is not None:
# 如果在个人信息页面获取到了学院班级
result.update({
"college_name": "无" if pending_result.get("学院名称:") == '' else pending_result["学院名称:"],
"major_name": "无" if pending_result.get("专业名称:") == '' else pending_result["专业名称:"],
"class_name": "无" if pending_result.get("班级名称:") == '' else pending_result["班级名称:"]
})
else:
# 如果个人信息页面获取不到学院班级,则此处需要请求另外一个地址以获取学院、专业、班级等信息
_url = urljoin(self.base_url, "/xszbbgl/xszbbgl_cxXszbbsqIndex.html?doType=details&gnmkdm=N106005")
_req_info = self.sess.post(
_url, headers=self.headers, cookies=self.cookies, timeout=self.timeout,
data={"offDetails": '1', "gnmkdm": "N106005", "czdmKey": "00"}
)
_doc = pq(_req_info.text)
if _doc("p.error_title").text() != "无功能权限,":
# 通过学生证补办申请入口,来补全部分信息
for ul_item in _doc.find("div.col-sm-6").items():
content = pq(ul_item).find('div.form-group')
key = pq(content).find('label.col-sm-4.control-label').text() + ':' # 为了保持格式一致,这里加个冒号
value = pq(content).find('div.col-sm-8 label.control-label').text()
# 到这一步,解析到的数据基本就是一个键值对形式的html数据了,比如"[学号:]:123456"
pending_result[key] = value
result.update({
"college_name": "无" if pending_result.get("学院:") is None else pending_result["学院:"],
"major_name": "无" if pending_result.get("专业:") is None else pending_result["专业:"],
"class_name": "无" if pending_result.get("班级:") is None else pending_result["班级:"],
})
return {"code": 1000, "msg": "获取个人信息成功", "data": result}
except exceptions.Timeout:
return {"code": 1003, "msg": "获取个人信息超时"}
except (
exceptions.RequestException,
json.decoder.JSONDecodeError,
AttributeError,
):
traceback.print_exc()
return {"code": 2333, "msg": "请重试,若多次失败可能是系统错误维护或需更新接口"}
except Exception as e:
traceback.print_exc()
return {"code": 999, "msg": "获取个人信息时未记录的错误:" + str(e)}
def get_grade(self, year: int, term: int = 0, use_personal_info: bool = False):
"""
获取成绩
use_personal_info: 是否使用获取个人信息接口获取成绩
"""
url = urljoin(
self.base_url,
"/cjcx/cjcx_cxDgXscj.html?doType=query&gnmkdm=N305005"
if use_personal_info
else "/cjcx/cjcx_cxXsgrcj.html?doType=query&gnmkdm=N305005",
)
temp_term = term
term = term**2 * 3
term = "" if term == 0 else term
data = {
"xnm": str(year), # 学年数
"xqm": str(term), # 学期数,第一学期为3,第二学期为12, 整个学年为空''
"_search": "false",
"nd": int(time.time() * 1000),
"queryModel.showCount": "100", # 每页最多条数
"queryModel.currentPage": "1",
"queryModel.sortName": "",
"queryModel.sortOrder": "asc",
"time": "0", # 查询次数
}
try:
req_grade = self.sess.post(
url,
headers=self.headers,
data=data,
cookies=self.cookies,
timeout=self.timeout,
)
if req_grade.status_code != 200:
return {"code": 2333, "msg": "教务系统挂了"}
doc = pq(req_grade.text)
if doc("h5").text() == "用户登录":
return {"code": 1006, "msg": "未登录或已过期,请重新登录"}
grade = req_grade.json()
grade_items = grade.get("items")
if not grade_items:
return {"code": 1005, "msg": "获取内容为空"}
result = {
"sid": grade_items[0]["xh"],
"name": grade_items[0]["xm"],
"year": year,
"term": temp_term,
"count": len(grade_items),
"courses": [
{
"course_id": i.get("kch_id"),
"title": i.get("kcmc"),
"teacher": i.get("jsxm"),
"class_name": i.get("jxbmc"),
"credit": self.align_floats(i.get("xf")),
"category": i.get("kclbmc"),
"nature": i.get("kcxzmc"),
"grade": self.parse_int(i.get("cj")),
"grade_point": self.align_floats(i.get("jd")),
"grade_nature": i.get("ksxz"),
"start_college": i.get("kkbmmc"),
"mark": i.get("kcbj"),
}
for i in grade_items
],
}
return {"code": 1000, "msg": "获取成绩成功", "data": result}
except exceptions.Timeout:
return {"code": 1003, "msg": "获取成绩超时"}
except (
exceptions.RequestException,
json.decoder.JSONDecodeError,
AttributeError,
):
traceback.print_exc()
return {"code": 2333, "msg": "请重试,若多次失败可能是系统错误维护或需更新接口"}
except Exception as e:
traceback.print_exc()
return {"code": 999, "msg": "获取成绩时未记录的错误:" + str(e)}
def get_schedule(self, year: int, term: int):
"""获取课程表信息"""
url = urljoin(self.base_url, "/kbcx/xskbcx_cxXsKb.html?gnmkdm=N2151")
temp_term = term
term = term**2 * 3
data = {"xnm": str(year), "xqm": str(term)}
try:
req_schedule = self.sess.post(
url,
headers=self.headers,
data=data,
cookies=self.cookies,
timeout=self.timeout,
)
if req_schedule.status_code != 200:
return {"code": 2333, "msg": "教务系统挂了"}
doc = pq(req_schedule.text)
if doc("h5").text() == "用户登录":
return {"code": 1006, "msg": "未登录或已过期,请重新登录"}
schedule = req_schedule.json()
if not schedule.get("kbList"):
return {"code": 1005, "msg": "获取内容为空"}
result = {
"sid": schedule["xsxx"].get("XH"),
"name": schedule["xsxx"].get("XM"),
"year": year,
"term": temp_term,
"count": len(schedule["kbList"]),
"courses": [
{
"course_id": i.get("kch_id"),
"title": i.get("kcmc"),
"teacher": i.get("xm"),
"class_name": i.get("jxbmc"),
"credit": self.align_floats(i.get("xf")),
"weekday": self.parse_int(i.get("xqj")),
"time": self.display_course_time(i.get("jc")),
"sessions": i.get("jc"),
"list_sessions": self.list_sessions(i.get("jc")),
"weeks": i.get("zcd"),
"list_weeks": self.list_weeks(i.get("zcd")),
"evaluation_mode": i.get("khfsmc"),
"campus": i.get("xqmc"),
"place": i.get("cdmc"),
"hours_composition": i.get("kcxszc"),
"weekly_hours": self.parse_int(i.get("zhxs")),
"total_hours": self.parse_int(i.get("zxs")),
}
for i in schedule["kbList"]
],
"extra_courses": [i.get("qtkcgs") for i in schedule.get("sjkList")],
}
result = self.split_merge_display(result)
return {"code": 1000, "msg": "获取课表成功", "data": result}
except exceptions.Timeout:
return {"code": 1003, "msg": "获取课表超时"}
except (
exceptions.RequestException,
json.decoder.JSONDecodeError,
AttributeError,
):
traceback.print_exc()
return {"code": 2333, "msg": "请重试,若多次失败可能是系统错误维护或需更新接口"}
except Exception as e:
traceback.print_exc()
return {"code": 999, "msg": "获取课表时未记录的错误:" + str(e)}
def get_academia(self):
"""获取学业生涯情况"""
url_main = urljoin(
self.base_url,
"/xsxy/xsxyqk_cxXsxyqkIndex.html?gnmkdm=N105515&layout=default",
)
url_info = urljoin(
self.base_url, "/xsxy/xsxyqk_cxJxzxjhxfyqKcxx.html?gnmkdm=N105515"
)
try:
req_main = self.sess.get(
url_main,
headers=self.headers,
cookies=self.cookies,
timeout=self.timeout,
stream=True,
)
if req_main.status_code != 200:
return {"code": 2333, "msg": "教务系统挂了"}
doc_main = pq(req_main.text)
if doc_main("h5").text() == "用户登录":
return {"code": 1006, "msg": "未登录或已过期,请重新登录"}
if str(doc_main("div.alert-danger")) != "":
return {"code": 998, "msg": doc_main("div.alert-danger").text()}
sid = doc_main("form#form input#xh_id").attr("value")
display_statistics = (
doc_main("div#alertBox").text().replace(" ", "").replace("\n", "")
)
sid = doc_main("input#xh_id").attr("value")
statistics = self.get_academia_statistics(display_statistics)
type_statistics = self.get_academia_type_statistics(req_main.text)
details = {}
for type in type_statistics.keys():
details[type] = self.sess.post(
url_info,
headers=self.headers,
data={"xfyqjd_id": type_statistics[type]["id"]},
cookies=self.cookies,
timeout=self.timeout,
stream=True,
).json()
result = {
"sid": sid,
"statistics": statistics,
"details": [
{
"type": type,
"credits": type_statistics[type]["credits"],
"courses": [
{
"course_id": i.get("KCH"),
"title": i.get("KCMC"),
"situation": self.parse_int(i.get("XDZT")),
"display_term": self.get_display_term(
sid, i.get("JYXDXNM"), i.get("JYXDXQMC")
),
"credit": self.align_floats(i.get("XF")),
"category": self.get_course_category(type, i),
"nature": i.get("KCXZMC"),
"max_grade": self.parse_int(i.get("MAXCJ")),
"grade_point": self.align_floats(i.get("JD")),
}
for i in details[type]
],
}
for type in type_statistics.keys()
if len(details[type]) > 0
],
}
return {"code": 1000, "msg": "获取学业情况成功", "data": result}
except exceptions.Timeout:
return {"code": 1003, "msg": "获取学业情况超时"}
except (
exceptions.RequestException,
json.decoder.JSONDecodeError,
AttributeError,
):
traceback.print_exc()
return {"code": 2333, "msg": "请重试,若多次失败可能是系统错误维护或需更新接口"}
except Exception as e:
traceback.print_exc()
return {"code": 999, "msg": "获取学业情况时未记录的错误:" + str(e)}
def get_academia_pdf(self):
"""获取学业生涯(学生成绩总表)pdf"""
url_view = urljoin(self.base_url, "/bysxxcx/xscjzbdy_dyXscjzbView.html")
url_window = urljoin(self.base_url, "/bysxxcx/xscjzbdy_dyCjdyszxView.html")
url_policy = urljoin(self.base_url, "/xtgl/bysxxcx/xscjzbdy_cxXsCount.html")
url_filetype = urljoin(self.base_url, "/bysxxcx/xscjzbdy_cxGswjlx.html")
url_common = urljoin(self.base_url, "/common/common_cxJwxtxx.html")
url_file = urljoin(self.base_url, "/bysxxcx/xscjzbdy_dyList.html")
url_progress = urljoin(self.base_url, "/xtgl/progress_cxProgressStatus.html")
data = {
"gsdygx": "10628-zw-mrgs",
"ids": "",
"bdykcxzDms": "",
"cytjkcxzDms": "",
"cytjkclbDms": "",
"cytjkcgsDms": "",
"bjgbdykcxzDms": "",
"bjgbdyxxkcxzDms": "",
"djksxmDms": "",
"cjbzmcDms": "",
"cjdySzxs": "",
"wjlx": "pdf",
}
try:
data_view = {"time": str(round(time.time() * 1000)), "gnmkdm": "N558020"}
data_params = data_view
del data_params["time"]
# View接口
req_view = self.sess.post(
url_view,
headers=self.headers,
data=data_view,
params=data_view,
cookies=self.cookies,
timeout=self.timeout,
)
if req_view.status_code != 200:
return {"code": 2333, "msg": "教务系统挂了"}
doc = pq(req_view.text)
if doc("h5").text() == "用户登录":
return {"code": 1006, "msg": "未登录或已过期,请重新登录"}
# Window接口
data_window = {"xh": ""}
self.sess.post(
url_window,
headers=self.headers,
data=data_window,
params=data_params,
cookies=self.cookies,
timeout=self.timeout,
)
# 许可接口
data_policy = data
del data_policy["wjlx"]
self.sess.post(
url_policy,
headers=self.headers,
data=data_policy,
params=data_params,
cookies=self.cookies,
timeout=self.timeout,
)
# 文件类型接口
data_filetype = data_policy
self.sess.post(
url_filetype,
headers=self.headers,
data=data_filetype,
params=data_params,
cookies=self.cookies,
timeout=self.timeout,
)
# Common接口
self.sess.post(
url_common,
headers=self.headers,
data=data_params,
params=data_params,
cookies=self.cookies,
timeout=self.timeout,
)
# 获取PDF文件URL
req_file = self.sess.post(
url_file,
headers=self.headers,
data=data,
params=data_params,
cookies=self.cookies,
timeout=self.timeout,
)
doc = pq(req_file.text)
if "错误" in doc("title").text():
error = doc("p.error_title").text()
return {"code": 998, "msg": error}
# 进度接口
data_progress = {
"key": "score_print_processed",
"gnmkdm": "N558020",
}
self.sess.post(
url_progress,
headers=self.headers,
data=data_progress,
params=data_progress,
cookies=self.cookies,
timeout=self.timeout,
)
# 生成PDF文件URL
pdf = (
req_file.text.replace("#成功", "")
.replace('"', "")
.replace("/", "\\")
.replace("\\\\", "/")
)
# 下载PDF文件
req_pdf = self.sess.get(
urljoin(self.base_url, pdf),
headers=self.headers,
cookies=self.cookies,
timeout=self.timeout + 2,
)
result = req_pdf.content # 二进制内容
return {"code": 1000, "msg": "获取学生成绩总表pdf成功", "data": result}
except exceptions.Timeout:
return {"code": 1003, "msg": "获取成绩总表pdf超时"}
except (
exceptions.RequestException,
json.decoder.JSONDecodeError,
AttributeError,
):
traceback.print_exc()
return {"code": 2333, "msg": "请重试,若多次失败可能是系统错误维护或需更新接口"}
except Exception as e:
traceback.print_exc()
return {"code": 999, "msg": "获取成绩总表pdf时未记录的错误:" + str(e)}
def get_schedule_pdf(self, year: int, term: int, name: str = "导出"):
"""获取课表pdf"""
url_policy = urljoin(self.base_url, "/kbdy/bjkbdy_cxXnxqsfkz.html")
url_file = urljoin(self.base_url, "/kbcx/xskbcx_cxXsShcPdf.html")
origin_term = term
term = term**2 * 3
data = {
"xm": name,
"xnm": str(year),
"xqm": str(term),
"xnmc": f"{year}-{year + 1}",
"xqmmc": str(origin_term),
"jgmc": "undefined",
"xxdm": "",
"xszd.sj": "true",
"xszd.cd": "true",
"xszd.js": "true",
"xszd.jszc": "false",
"xszd.jxb": "true",
"xszd.xkbz": "true",
"xszd.kcxszc": "true",
"xszd.zhxs": "true",
"xszd.zxs": "true",
"xszd.khfs": "true",
"xszd.xf": "true",
"xszd.skfsmc": "false",
"kzlx": "dy",
}
try:
# 许可接口
pilicy_params = {"gnmkdm": "N2151"}
req_policy = self.sess.post(
url_policy,
headers=self.headers,
data=data,
params=pilicy_params,
cookies=self.cookies,
timeout=self.timeout,
)
if req_policy.status_code != 200:
return {"code": 2333, "msg": "教务系统挂了"}
doc = pq(req_policy.text)
if doc("h5").text() == "用户登录":
return {"code": 1006, "msg": "未登录或已过期,请重新登录"}
# 获取PDF文件URL
file_params = {"doType": "table"}
req_file = self.sess.post(
url_file,
headers=self.headers,
data=data,
params=file_params,
cookies=self.cookies,
timeout=self.timeout,
)
doc = pq(req_file.text)
if "错误" in doc("title").text():
error = doc("p.error_title").text()
return {"code": 998, "msg": error}
result = req_file.content # 二进制内容
return {"code": 1000, "msg": "获取课程表pdf成功", "data": result}
except exceptions.Timeout:
return {"code": 1003, "msg": "获取课程表pdf超时"}
except (
exceptions.RequestException,
json.decoder.JSONDecodeError,
AttributeError,
):
traceback.print_exc()
return {"code": 2333, "msg": "请重试,若多次失败可能是系统错误维护或需更新接口"}
except Exception as e:
traceback.print_exc()
return {"code": 999, "msg": "获取课程表pdf时未记录的错误:" + str(e)}
def get_notifications(self):
"""获取通知消息"""
url = urljoin(self.base_url, "/xtgl/index_cxDbsy.html?doType=query")
data = {
"sfyy": "0", # 是否已阅,未阅未1,已阅为2
"flag": "1",
"_search": "false",
"nd": int(time.time() * 1000),
"queryModel.showCount": "1000", # 最多条数
"queryModel.currentPage": "1", # 当前页数
"queryModel.sortName": "cjsj",
"queryModel.sortOrder": "desc", # 时间倒序, asc正序
"time": "0",
}
try:
req_notification = self.sess.post(
url,
headers=self.headers,
data=data,
cookies=self.cookies,
timeout=self.timeout,
)
if req_notification.status_code != 200:
return {"code": 2333, "msg": "教务系统挂了"}
doc = pq(req_notification.text)
if doc("h5").text() == "用户登录" or "错误" in doc("title").text():
return {"code": 1006, "msg": "未登录或已过期,请重新登录"}
notifications = req_notification.json()
result = [
{**self.split_notifications(i), "create_time": i.get("cjsj")}
for i in notifications.get("items")
]
return {"code": 1000, "msg": "获取消息成功", "data": result}
except exceptions.Timeout:
return {"code": 1003, "msg": "获取消息超时"}
except (
exceptions.RequestException,
json.decoder.JSONDecodeError,
AttributeError,
):
traceback.print_exc()
return {"code": 2333, "msg": "请重试,若多次失败可能是系统错误维护或需更新接口"}
except Exception as e:
traceback.print_exc()
return {"code": 999, "msg": "获取消息时未记录的错误:" + str(e)}
def get_selected_courses(self, year: int, term: int):
"""获取已选课程信息"""
try:
url = urljoin(
self.base_url,
"/xsxk/zzxkyzb_cxZzxkYzbChoosedDisplay.html?gnmkdm=N253512",
)
temp_term = term
term = term**2 * 3
data = {"xkxnm": str(year), "xkxqm": str(term)}
req_selected = self.sess.post(
url,
data=data,
headers=self.headers,
cookies=self.cookies,
timeout=self.timeout,
)
if req_selected.status_code != 200:
return {"code": 2333, "msg": "教务系统挂了"}
doc = pq(req_selected.text)
if doc("h5").text() == "用户登录":
return {"code": 1006, "msg": "未登录或已过期,请重新登录"}
selected = req_selected.json()
result = {
"year": year,
"term": temp_term,
"count": len(selected),
"courses": [
{
"course_id": i.get("kch"),
"class_id": i.get("jxb_id"),
"do_id": i.get("do_jxb_id"),
"title": i.get("kcmc"),
"teacher_id": (re.findall(r"(.*?\d+)/", i.get("jsxx")))[0],
"teacher": (re.findall(r"/(.*?)/", i.get("jsxx")))[0],
"credit": float(i.get("xf", 0)),
"category": i.get("kklxmc"),
"capacity": int(i.get("jxbrs", 0)),
"selected_number": int(i.get("yxzrs", 0)),
"place": self.get_place(i.get("jxdd")),
"time": self.get_course_time(i.get("sksj")),
"optional": int(i.get("zixf", 0)),
"waiting": i.get("sxbj"),
}
for i in selected
],
}
return {"code": 1000, "msg": "获取已选课程成功", "data": result}
except exceptions.Timeout:
return {"code": 1003, "msg": "获取已选课程超时"}
except (
exceptions.RequestException,
json.decoder.JSONDecodeError,
AttributeError,
):
traceback.print_exc()
return {"code": 2333, "msg": "请重试,若多次失败可能是系统错误维护或需更新接口"}
except Exception as e:
traceback.print_exc()
return {"code": 999, "msg": f"获取已选课程时未记录的错误:{str(e)}"}
def get_block_courses(self, year: int, term: int, block: int):
"""获取板块课选课列表"""
# TODO: 优化代码
try:
# 获取head_data
url_head = urljoin(
self.base_url,
"/xsxk/zzxkyzb_cxZzxkYzbIndex.html?gnmkdm=N253512&layout=default",
)
req_head_data = self.sess.get(
url_head,
headers=self.headers,
cookies=self.cookies,
timeout=self.timeout,
)
if req_head_data.status_code != 200:
return {"code": 2333, "msg": "教务系统挂了"}
doc = pq(req_head_data.text)
if doc("h5").text() == "用户登录":
return {"code": 1006, "msg": "未登录或已过期,请重新登录"}
if str(doc("div.nodata")) != "":
return {"code": 998, "msg": doc("div.nodata").text()}
got_credit_list = [i for i in doc("font[color='red']").items()]
if len(got_credit_list) == 0:
return {"code": 1005, "msg": "板块课内容为空"}
head_data = {"got_credit": got_credit_list[2].string}
kklxdm_list = []
xkkz_id_list = []
for tab_content in doc("a[role='tab']").items():
onclick_content = tab_content.attr("onclick")
r = re.findall(r"'(.*?)'", str(onclick_content))
kklxdm_list.append(r[0].strip())
xkkz_id_list.append(r[1].strip())
head_data["bkk1_kklxdm"] = kklxdm_list[0]
head_data["bkk2_kklxdm"] = kklxdm_list[1]
head_data["bkk3_kklxdm"] = kklxdm_list[2]
head_data["bkk1_xkkz_id"] = xkkz_id_list[0]
head_data["bkk2_xkkz_id"] = xkkz_id_list[1]
head_data["bkk3_xkkz_id"] = xkkz_id_list[2]
for head_data_content in doc("input[type='hidden']"):
name = head_data_content.attr("name")
value = head_data_content.attr("value")
head_data[str(name)] = str(value)
url_display = urljoin(
self.base_url, "/xsxk/zzxkyzb_cxZzxkYzbDisplay.html?gnmkdm=N253512"
)
display_req_data = {
"xkkz_id": head_data[f"bkk{block}_xkkz_id"],
"xszxzt": "1",
"kspage": "0",
}
req_display_data = self.sess.post(
url_display,
headers=self.headers,
data=display_req_data,
cookies=self.cookies,
timeout=self.timeout,
)
doc_display = pq(req_display_data.text)
display_data = {}
for display_data_content in doc_display("input[type='hidden']").items():
name = display_data_content.get("name")
value = display_data_content.get("value")
display_data[str(name)] = str(value)
head_data.update(display_data)
# 获取课程列表
url_kch = urljoin(
self.base_url, "/xsxk/zzxkyzb_cxZzxkYzbPartDisplay.html?gnmkdm=N253512"
)
url_bkk = urljoin(
self.base_url, "/xsxk/zzxkyzb_cxJxbWithKchZzxkYzb.html?gnmkdm=N253512"
)
term = term**2 * 3
kch_data = {
"bklx_id": head_data["bklx_id"],
"xqh_id": head_data["xqh_id"],
"zyfx_id": head_data["zyfx_id"],
"njdm_id": head_data["njdm_id"],
"bh_id": head_data["bh_id"],
"xbm": head_data["xbm"],
"xslbdm": head_data["xslbdm"],
"ccdm": head_data["ccdm"],
"xsbj": head_data["xsbj"],
"xkxnm": str(year),
"xkxqm": str(term),
"kklxdm": head_data[f"bkk{block}_kklxdm"],
"kkbk": head_data["kkbk"],
"rwlx": head_data["rwlx"],
"kspage": "1",
"jspage": "10",
}
kch_res = self.sess.post(
url_kch,
headers=self.headers,
data=kch_data,
cookies=self.cookies,
timeout=self.timeout,
)
jkch_res = kch_res.json()
bkk_data = {
"bklx_id": head_data["bklx_id"],
"xkxnm": str(year),
"xkxqm": str(term),
"xkkz_id": head_data[f"bkk{block}_xkkz_id"],
"xqh_id": head_data["xqh_id"],
"zyfx_id": head_data["zyfx_id"],
"njdm_id": head_data["njdm_id"],
"bh_id": head_data["bh_id"],
"xbm": head_data["xbm"],
"xslbdm": head_data["xslbdm"],
"ccdm": head_data["ccdm"],