-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathcourseGrabber.js
More file actions
2957 lines (2633 loc) · 99.4 KB
/
courseGrabber.js
File metadata and controls
2957 lines (2633 loc) · 99.4 KB
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
// 仓库地址(持续维护、更新中): https://github.com/ceilf6/Auto_courseGrabber
// https://github.com/ceilf6
// https://blog.csdn.net/2301_78856868
// 使用方法:
// 1. 登录教务系统并进入选课页面
// 2. 配置目标课程列表 TARGET_COURSES(现在已经支持UI界面,所以在UI界面上配置也没事)
// 3. 按F12打开控制台,粘贴此脚本并执行
// 4. 输入 grab.start() 开始抢课
// 注意!!! 目标课程得在页面中出现(可以在不是选课时间到目标课程展示的页面并打开定时开抢功能、教学班卡片信息本脚本已经自动实现展开所以不重要),DOM树一定得展开否则无法找到 !!!
(function () {
// ========= 防止重复粘贴/重复执行 =========
const __CG_GLOBAL__ = typeof window !== "undefined" ? window : globalThis;
const __CG_LOADED_KEY__ = "__AUTO_COURSE_GRABBER_LOADED__";
const __CG_INSTANCE_KEY__ = "__AUTO_COURSE_GRABBER_INSTANCE_ID__";
const __CG_REFRESH_LOCK_KEY__ = "__AUTO_COURSE_GRABBER_LAST_REFRESH_AT__";
if (__CG_GLOBAL__[__CG_LOADED_KEY__]) {
try {
// 尝试停止旧实例(如果旧实例仍挂在 window.grab 上)
if (__CG_GLOBAL__.grab && typeof __CG_GLOBAL__.grab.stop === "function") {
__CG_GLOBAL__.grab.stop();
}
} catch (e) {
// 忽略停止失败
}
console.warn(
"[抢课脚本] 检测到脚本已加载过一次:已尝试停止旧实例,并将覆盖为新实例。",
);
}
__CG_GLOBAL__[__CG_LOADED_KEY__] = true;
__CG_GLOBAL__[__CG_INSTANCE_KEY__] =
`${Date.now()}-${Math.random().toString(16).slice(2)}`;
("use strict");
// ========== 防御性地保存原生方法引用 ==========
// 在脚本执行前保存原生的 Array.prototype.filter,防止被页面污染
// 假如使用猴子补丁,可能会导致原先系统中的功能出错,还是选择耦合度低、入侵性小的方案
const nativeArrayFilter = Array.prototype.filter;
const nativeArrayMap = Array.prototype.map;
/**
* 安全的数组 filter 函数
* 使用保存的原生 filter 方法,避免被页面污染
* @param {Array} array - 要过滤的数组
* @param {Function} callback - 过滤回调函数
* @returns {Array} - 过滤后的数组
*/
function safeFilter(array, callback) {
if (!array || !Array.isArray(array)) {
return [];
}
try {
return nativeArrayFilter.call(array, callback);
} catch (e) {
// 如果原生方法也失败,回退到手动循环
const result = [];
for (let i = 0; i < array.length; i++) {
try {
if (callback(array[i], i, array)) {
result.push(array[i]);
}
} catch (err) {
// 忽略回调执行失败的项
}
}
return result;
}
}
/**
* 安全的数组 map 函数
* 使用保存的原生 map 方法,避免被页面污染
* @param {Array} array - 要映射的数组
* @param {Function} callback - 映射回调函数
* @returns {Array} - 映射后的数组
*/
function safeMap(array, callback) {
if (!array || !Array.isArray(array)) {
return [];
}
try {
return nativeArrayMap.call(array, callback);
} catch (e) {
// 如果原生方法也失败,回退到手动循环
const result = [];
for (let i = 0; i < array.length; i++) {
try {
result.push(callback(array[i], i, array));
} catch (err) {
result.push(undefined);
}
}
return result;
}
}
// ========== 配置参数 ==========
// 支持多门课程同时抢课,格式: [{code: '课程号或课程名称', priority: 优先级, timeFilter: 时间过滤, teacherFilter: 教师过滤}]
// code 字段支持两种输入方式:
// 1. 课程号(纯数字):如 '23286514'
// 2. 课程名称(包含中文):如 '机器学习'、'计算机控制'
const TARGET_COURSES = [
// 示例配置:
// { code: '23286514', priority: 1 }, // 使用课程号,高优先级,无过滤
// { code: '机器学习', priority: 1 }, // 使用课程名称,高优先级,无过滤
// { code: 'CS102', priority: 2, timeFilter: ['星期一', '星期三'] }, // 只选星期一或星期三的课
// { code: 'CS103', priority: 3, teacherFilter: ['张三', '李四'] } // 只选张三或李四的课
// { code: 'CS104', priority: 4, timeFilter: ['第1-2节'], teacherFilter: ['王五'] } // 同时过滤时间和教师
];
const CHECK_INTERVAL = 1000; // 检查间隔(毫秒)
const MAX_ATTEMPTS = 3000; // 最大尝试次数
const MAX_FAILED_ATTEMPTS = 10; // 最大连续失败次数
const RETRY_DELAY = 3000; // 重试延迟(毫秒)
const CONCURRENT_ENABLED = true; // 是否启用并发抢课
const CLICK2EXPEND_ENABLED = true; // 用户设置: 是否在 jQuery 后自动展开目标课程信息,用于时间筛选和教师筛选
let click2expend_enabled = true; // 用于脚本自动关闭
// ========== 过滤器配置 ==========
// 全局时间过滤器(可选)- 留空表示不过滤,支持多个关键词,满足任意一个即可
// 示例: ['星期一', '星期三', '第1-2节', '第11-12节']
const GLOBAL_TIME_FILTER = [];
// 全局教师过滤器(可选)- 留空表示不过滤,支持多个关键词,满足任意一个即可
// 示例: ['张三', '张三', '讲师']
const GLOBAL_TEACHER_FILTER = [];
// ========== 全局状态管理 ==========
let attemptCount = 0;
let isRunning = false;
let intervalId = null;
let refreshInProgress = false; // 避免刷新分支在 attemptCount 未变化时被重复触发
let refreshTimeoutId = null; // 刷新后延迟抢课的 timeout
// 多课程状态管理
let courseStates = new Map(); // 每门课程的状态: {courseCode: {attempts, failed, tried, conflicted, selecting, success}}
let selectedCourses = new Set(); // 已成功选上的课程
let activeCourses = new Set(); // 当前活跃的课程列表
// 全局选课队列
let selectingQueue = []; // 正在处理的选课任务队列
let isProcessingQueue = false; // 是否正在处理队列
// 定时开抢相关
let scheduledTime = null; // 计划开抢时间
let schedulerIntervalId = null; // 定时器ID
let isScheduled = false; // 是否已设置定时
// ========== 工具函数 ==========
/**
* 安全的字符串分割与过滤函数
* 使用安全的 filter 函数避免被页面污染
* @param {string} input - 原始输入字符串
* @param {RegExp} [separatorRegex=/[,,;;]+/] - 分隔符正则
* @returns {string[]} - 过滤后的非空字符串数组
*/
function safeParseFilterInput(input, separatorRegex = /[,,;;]+/) {
if (!input || typeof input !== "string") {
return [];
}
const raw = input.trim();
if (!raw) {
return [];
}
// 分割字符串
const splitResult = raw.split(separatorRegex);
// Trim 每个元素并过滤空字符串
const trimmed = safeMap(splitResult, (item) => {
try {
return String(item).trim();
} catch (e) {
return String(item);
}
});
// 过滤空字符串
return safeFilter(trimmed, (v) => {
try {
const str = String(v);
return str && str.length > 0;
} catch (e) {
return false;
}
});
}
/**
* 判断输入是否为课程号(纯数字)
* @param {string} input - 用户输入
* @returns {boolean} - 是否为课程号
*/
function isCourseCode(input) {
return /^\d+$/.test(String(input).trim());
}
/**
* 从教学班名称中提取课程名称
* 教学班名称格式:课程名称-0001
* @param {string} jxbmc - 教学班名称
* @returns {string} - 课程名称
*/
function extractCourseNameFromJxbmc(jxbmc) {
if (!jxbmc) return "";
// 移除末尾的 -数字 部分
const match = jxbmc.match(/^(.+)-\d+$/);
return match ? match[1].trim() : jxbmc.trim();
}
/**
* 展开课程详情(支持课程号和课程名称)
* @param {string} courseCodeOrName - 课程号或课程名称
* @returns {boolean} - 是否成功展开
*/
function expandCourseByCode(courseCodeOrName) {
// 找所有课程头
const heads = document.querySelectorAll(".panel-heading.kc_head");
const input = String(courseCodeOrName).trim();
const isCode = isCourseCode(input);
for (let head of heads) {
let matched = false;
if (isCode) {
// 按课程号匹配
const codeInput = head.querySelector('input[name="kch_id"]');
if (codeInput && codeInput.value === input) {
matched = true;
}
} else {
// 按课程名称匹配
// 课程名称在 span.kcmc 下的 <a> 标签内,格式:(课程号)课程名称
const kcmcSpan = head.querySelector("span.kcmc");
if (kcmcSpan) {
const kcmcLink = kcmcSpan.querySelector("a");
if (kcmcLink) {
const courseName = kcmcLink.textContent.trim();
// 宽松匹配:只要a元素内容包含用户输入就匹配(不区分大小写)
if (courseName.toLowerCase().includes(input.toLowerCase())) {
matched = true;
}
}
}
}
/*
<div class="panel-heading kc_head" onclick="loadJxbxxZzxk(this)"
style="background-color:#C1FFC1;">
<h3 class="panel-title"><span class="kcmc" id="kcmc_23005523">(23005523)<a
href="javascript:void(0);"
onclick="showCourseInfo('23005523')">质量管理</a><i class="l-kc-xf"
style="display: inline;"> - <i id="xf_23005523">5.0</i>
学分</i></span><span>教学班个数:<font class="jxbgsxx">4</font></span><span
id="zt_txt_23005523">状态:<b>已选</b></span></h3><input type="hidden"
name="kch_id" value="23005523"><input type="hidden" name="kcxzzt"
id="kcxzzt_23005523" value="1"><input type="hidden" name="cxbj"
id="cxbj_23005523" value="0"><input type="hidden" name="fxbj" id="fxbj_23005523"
value="0"><input type="hidden" name="xxkbj" id="xxkbj_23005523" value="0"><input
type="hidden" name="czzt" value="0"><a href="javascript:void(0);"
class="expand_close expand1">展开关闭</a>
</div>
*/
if (matched) {
// 直接触发 click(等价于用户点击)
head.click();
return true;
}
}
return false;
}
function forceExpandTargetCourses() {
const targets = new Set([
...activeCourses,
...TARGET_COURSES.map((c) => (typeof c === "string" ? c : c.code)),
]);
targets.forEach((code) => {
expandCourseByCode(code);
});
}
function forceExpandTargetCoursesAggressive() {
let count = 0;
const timer = setInterval(() => {
forceExpandTargetCourses();
if (++count >= 3) clearInterval(timer);
}, 300);
}
// 彩色日志函数
function log(message, type = "info", courseCode = null) {
const timestamp = new Date().toLocaleTimeString();
const courseTag = courseCode ? `[${courseCode}]` : "";
const prefix = `[抢课脚本 ${timestamp}]${courseTag}`;
switch (type) {
case "success":
console.log(
`%c${prefix} ✅ ${message}`,
"color: #00ff00; font-weight: bold;",
);
break;
case "error":
console.log(
`%c${prefix} ❌ ${message}`,
"color: #ff0000; font-weight: bold;",
);
break;
case "warning":
console.log(
`%c${prefix} ⚠️ ${message}`,
"color: #ffa500; font-weight: bold;",
);
break;
case "info":
console.log(`%c${prefix} ℹ️ ${message}`, "color: #0099ff;");
break;
}
}
// 初始化课程状态
function initCourseState(courseCode) {
if (!courseStates.has(courseCode)) {
courseStates.set(courseCode, {
attempts: 0,
failed: 0,
tried: new Set(),
conflicted: new Set(),
selecting: false,
success: false,
lastAttempt: 0,
});
}
return courseStates.get(courseCode);
}
// 获取课程状态
function getCourseState(courseCode) {
return courseStates.get(courseCode) || initCourseState(courseCode);
}
// 检查是否所有课程都已完成(成功或失败)
function allCoursesCompleted() {
for (let courseCode of activeCourses) {
const state = getCourseState(courseCode);
if (!state.success && state.failed < MAX_FAILED_ATTEMPTS) {
return false;
}
}
return true;
}
// 时间模糊匹配函数
function matchesTimeFilter(timeInfo, timeFilter) {
// 如果没有配置过滤器,返回true(不过滤)
if (!timeFilter || timeFilter.length === 0) {
return true;
}
// 如果时间信息为空,返回false
if (!timeInfo || timeInfo === "未知时间") {
return false;
}
// 检查是否匹配任意一个时间关键词
for (let keyword of timeFilter) {
if (timeInfo.includes(keyword)) {
return true;
}
}
return false;
}
// 教师模糊匹配函数
function matchesTeacherFilter(teacher, teacherFilter) {
// 如果没有配置过滤器,返回true(不过滤)
if (!teacherFilter || teacherFilter.length === 0) {
return true;
}
// 如果教师信息为空,返回false
if (!teacher || teacher === "未知教师") {
return false;
}
// 检查是否匹配任意一个教师关键词
for (let keyword of teacherFilter) {
if (teacher.includes(keyword)) {
return true;
}
}
return false;
}
// 检查教学班是否匹配过滤条件
function matchesFilters(teachingClass, courseCode) {
// 获取该课程的配置
const courseConfig = TARGET_COURSES.find((c) => c.code === courseCode);
// 获取时间和教师过滤器(优先使用课程特定配置,否则使用全局配置)
const timeFilter =
(courseConfig && courseConfig.timeFilter) || GLOBAL_TIME_FILTER;
const teacherFilter =
(courseConfig && courseConfig.teacherFilter) || GLOBAL_TEACHER_FILTER;
// 检查时间过滤
const timeMatch = matchesTimeFilter(
teachingClass.info.timeInfo,
timeFilter,
);
if (!timeMatch) {
return { match: false, reason: "时间不匹配过滤条件" };
}
// 检查教师过滤
const teacherMatch = matchesTeacherFilter(
teachingClass.info.teacher,
teacherFilter,
);
if (!teacherMatch) {
return { match: false, reason: "教师不匹配过滤条件" };
}
return { match: true, reason: "通过过滤" };
}
/**
* 检查教学班行是否匹配目标课程(支持课程号和课程名称)
* @param {HTMLElement} row - 教学班行元素
* @param {string} targetCourseCodeOrName - 课程号或课程名称
* @returns {boolean} - 是否匹配
*/
function isRowMatchingCourse(row, targetCourseCodeOrName) {
const input = String(targetCourseCodeOrName).trim();
const isCode = isCourseCode(input);
if (isCode) {
// 按课程号匹配:检查 td.kch_id
const kchIdCell = row.querySelector("td.kch_id");
if (kchIdCell && kchIdCell.textContent.trim() === input) {
return true;
}
} else {
// 按课程名称匹配:检查 td.jxbmc 中的教学班名称
const jxbmcCell = row.querySelector("td.jxbmc");
if (jxbmcCell) {
const jxbmcText = jxbmcCell.textContent.trim();
const courseName = extractCourseNameFromJxbmc(jxbmcText);
// 精确匹配或包含匹配
if (
courseName === input ||
courseName.includes(input) ||
input.includes(courseName)
) {
return true;
}
}
}
return false;
}
// 查找目标课程的所有教学班(支持课程号和课程名称)
function findAllTeachingClasses(targetCourseCodeOrName) {
const teachingClasses = [];
const input = String(targetCourseCodeOrName).trim();
const isCode = isCourseCode(input);
// 方法1:直接遍历所有教学班行,按课程号或课程名称匹配
const allRows = document.querySelectorAll("table tbody tr.body_tr");
for (let row of allRows) {
if (isRowMatchingCourse(row, input)) {
const selectButton = row.querySelector(
'button, a, input[type="button"]',
);
if (selectButton) {
const classInfo = extractTeachingClassInfo(row);
if (classInfo && classInfo.id) {
teachingClasses.push({
row: row,
info: classInfo,
button: selectButton,
courseCode: targetCourseCodeOrName,
});
}
}
}
}
// 方法2:如果方法1没找到,尝试通过课程区域查找
if (teachingClasses.length === 0) {
// 查找包含目标课程的所有元素
const allElements = document.querySelectorAll("*");
let courseSection = null;
// 首先找到课程主行
for (let element of allElements) {
const text = element.textContent || "";
if (isCode) {
// 课程号匹配
if (text.includes(`(${input})`) || text.includes(input)) {
courseSection = element.closest("div, section, table");
break;
}
} else {
// 课程名称匹配
if (text.includes(input)) {
courseSection = element.closest("div, section, table");
break;
}
}
}
if (!courseSection) {
// 如果没找到课程区域,尝试表格行方式
const courseRows = document.querySelectorAll("table tbody tr");
for (let row of courseRows) {
if (isRowMatchingCourse(row, input)) {
// 找到匹配的行,查找同一表格中的所有教学班
const table = row.closest("table");
if (table) {
const tableRows = table.querySelectorAll("tbody tr");
for (let classRow of tableRows) {
if (isRowMatchingCourse(classRow, input)) {
const selectButton = classRow.querySelector(
'button, a, input[type="button"]',
);
if (selectButton) {
const classInfo = extractTeachingClassInfo(classRow);
if (classInfo && classInfo.id) {
teachingClasses.push({
row: classRow,
info: classInfo,
button: selectButton,
courseCode: targetCourseCodeOrName,
});
}
}
}
}
}
break;
}
}
} else {
// 在课程区域内查找所有教学班行
const classRows = courseSection.querySelectorAll("tr");
for (let row of classRows) {
const selectButton = row.querySelector(
'button, a, input[type="button"]',
);
if (selectButton) {
const classInfo = extractTeachingClassInfo(row);
if (classInfo && classInfo.id) {
teachingClasses.push({
row: row,
info: classInfo,
button: selectButton,
courseCode: targetCourseCodeOrName,
});
}
}
}
}
}
log(
`找到 ${teachingClasses.length} 个教学班`,
"info",
targetCourseCodeOrName,
);
return teachingClasses;
}
// 查找所有目标课程的教学班
function findAllCoursesTeachingClasses() {
const allClasses = new Map(); // courseCode -> teachingClasses[]
for (let courseCode of activeCourses) {
const classes = findAllTeachingClasses(courseCode);
if (classes.length > 0) {
allClasses.set(courseCode, classes);
}
}
return allClasses;
}
// 提取教学班信息
function extractTeachingClassInfo(row) {
try {
let className = "";
let teacher = "";
let capacity = "";
let timeInfo = "";
// 记录原始文本用于调试
const fullText = row.textContent || row.innerText || "";
// 优先使用表格特定类名提取信息(更准确)
// .jxbmc - 教学班名称
const jxbmcEl = row.querySelector(".jxbmc, td.jxbmc");
if (jxbmcEl) {
className = jxbmcEl.textContent.trim();
}
// .jsxmzc - 上课教师(格式:【教师名】职称)
const jsxmzcEl = row.querySelector(".jsxmzc, td.jsxmzc");
if (jsxmzcEl) {
teacher = jsxmzcEl.textContent.trim();
}
// .sksj - 上课时间
const sksjEl = row.querySelector(".sksj, td.sksj");
if (sksjEl) {
timeInfo = sksjEl.textContent.trim();
}
// .rsxx - 已选/容量(格式:【36/50】)
const rsxxEl = row.querySelector(".rsxx, td.rsxx");
if (rsxxEl) {
capacity = rsxxEl.textContent.trim();
}
// 如果通过类名没找到,回退到遍历所有单元格
if (!className || !teacher || !capacity || !timeInfo) {
const cells = row.querySelectorAll("td");
for (let cell of cells) {
const text = cell.textContent.trim();
// 提取教学班名称(如:工程化学-0001)
if (!className && text.includes("-") && text.match(/\d{4}/)) {
className = text;
}
// 提取教师信息
if (!teacher && text.includes("【") && text.includes("】")) {
teacher = text;
}
// 提取容量信息 - 只选择数字/数字格式
if (!capacity && text.match(/\d+\/\d+/)) {
capacity = text;
}
// 提取时间信息
if (
!timeInfo &&
(text.includes("星期") ||
text.includes("第") ||
text.includes("节"))
) {
timeInfo = text;
}
}
}
// 如果仍未找到基本信息,尝试从整个行文本中提取
if (!className || !teacher || !capacity) {
// 尝试提取教学班名称
if (!className) {
const classMatch = fullText.match(/([^-\s]+[-]\d{4})/);
if (classMatch) {
className = classMatch[1];
}
}
// 尝试提取教师
if (!teacher) {
const teacherMatch = fullText.match(/【([^】]+)】/);
if (teacherMatch) {
teacher = `【${teacherMatch[1]}】`;
}
}
// 尝试提取容量
if (!capacity) {
const capacityMatch = fullText.match(/(\d+\/\d+|已满)/);
if (capacityMatch) {
capacity = capacityMatch[1];
}
}
// 尝试提取时间
if (!timeInfo) {
const timeMatch = fullText.match(/(星期[一二三四五六日][^星期]*)/g);
if (timeMatch) {
timeInfo = timeMatch.join(" ");
}
}
}
// 更宽松的信息检查 - 只要有按钮就认为是有效的教学班
const hasButton =
row.querySelector('button, a, input[type="button"]') !== null;
// 生成唯一ID(优先使用 jxb_id)
const jxbIdEl = row.querySelector(".jxb_id, div.jxb_id");
const jxbId = jxbIdEl ? jxbIdEl.textContent.trim() : "";
const uniqueId =
jxbId ||
className ||
teacher ||
capacity ||
fullText.substring(0, 20) ||
`row_${Date.now()}_${Math.random()}`;
const result = {
className: className || "未知教学班",
teacher: teacher || "未知教师",
capacity: capacity || "未知容量",
timeInfo: timeInfo || "未知时间",
id: `${uniqueId}_${teacher || "unknown"}`,
jxbId: jxbId, // 保存教学班ID,可能用于后续操作
hasButton: hasButton,
rawText: fullText.substring(0, 200), // 保留原始文本用于调试
};
return result;
} catch (error) {
// 返回默认信息而不是null
return {
className: "解析失败",
teacher: "未知教师",
capacity: "未知容量",
timeInfo: "未知时间",
id: `error_${Date.now()}_${Math.random()}`,
jxbId: "",
hasButton: false,
rawText: (row.textContent || "").substring(0, 200),
};
}
}
// 检查教学班是否可选课
// 逻辑:只判断 .full 元素("已满"标识)是否显示
function checkTeachingClassCapacity(teachingClass) {
try {
if (!teachingClass || !teachingClass.row) {
return false;
}
// 检查 .full 元素是否可见
const fullElement = teachingClass.row.querySelector(".full, td.full");
if (fullElement) {
const style = window.getComputedStyle(fullElement);
const isVisible =
style.display !== "none" && style.visibility !== "hidden";
// 如果"已满"可见,返回 false
if (isVisible) {
return false;
}
}
// "已满"不可见,可以选课
return true;
} catch (error) {
return false;
}
}
// 检查是否出现时间冲突警告
function checkTimeConflictWarning() {
try {
// 检查页面中是否出现时间冲突警告
const warningTexts = [
"所选教学班的上课时间与其他教学班有冲突",
"上课时间与其他教学班有冲突",
"时间冲突",
"时间有冲突",
];
// 查找所有可能包含警告文本的元素
const allElements = document.querySelectorAll("*");
for (let element of allElements) {
const text = element.textContent || element.innerText || "";
for (let warningText of warningTexts) {
if (text.includes(warningText)) {
return true;
}
}
}
// 检查弹窗或模态框中的警告
const modals = document.querySelectorAll(
'.modal, .dialog, .alert, [role="dialog"], [role="alert"]',
);
for (let modal of modals) {
const modalText = modal.textContent || modal.innerText || "";
for (let warningText of warningTexts) {
if (modalText.includes(warningText)) {
return true;
}
}
}
return false;
} catch (error) {
return false;
}
}
// 退选指定课程
function dropCourse(courseCode) {
return new Promise((resolve) => {
try {
log(`🔄 开始退选课程: ${courseCode}`, "info", courseCode);
// 查找该课程的所有教学班
const teachingClasses = findAllTeachingClasses(courseCode);
if (teachingClasses.length === 0) {
log(`未找到课程 ${courseCode} 的教学班`, "warning", courseCode);
resolve(false);
return;
}
// 查找包含"退选"按钮的教学班
let dropClass = null;
for (let tc of teachingClasses) {
const rowText = tc.row ? tc.row.textContent : "";
if (rowText.includes("退选")) {
dropClass = tc;
break;
}
}
if (!dropClass) {
log(`课程 ${courseCode} 未找到可退选的教学班`, "warning", courseCode);
resolve(false);
return;
}
// 查找退选按钮
const row = dropClass.row;
const allElements = row.querySelectorAll("*");
let dropButton = null;
for (let element of allElements) {
const elementText = element.textContent.trim();
if (elementText === "退选" || elementText.includes("退选")) {
if (
element.tagName === "BUTTON" ||
element.tagName === "A" ||
element.onclick ||
element.getAttribute("onclick")
) {
dropButton = element;
break;
}
}
}
if (!dropButton) {
log(`未找到课程 ${courseCode} 的退选按钮`, "warning", courseCode);
resolve(false);
return;
}
log(`找到退选按钮,正在点击...`, "info", courseCode);
dropButton.click();
// 等待模态框出现并确认退选
setTimeout(() => {
log(`等待退选确认模态框...`, "info", courseCode);
// 多种方式查找模态框中的确定按钮
let confirmButton = null;
// 方法1: 查找模态框内的确定按钮(优先)
const modals = document.querySelectorAll(
'.modal, .bootbox, [role="dialog"]',
);
for (let modal of modals) {
// 检查模态框是否包含退选相关文本
const modalText = modal.textContent || "";
if (modalText.includes("退选") || modalText.includes("你是否")) {
// 在这个模态框内查找确定按钮
const buttons = modal.querySelectorAll(
'button, input[type="button"], a',
);
for (let btn of buttons) {
const btnText = btn.textContent.trim();
const btnId = btn.id || "";
const btnHandler = btn.getAttribute("data-bb-handler") || "";
// 匹配确定按钮的多种特征
if (
btnText.includes("确定") ||
btnText.includes("确认") ||
btnText.includes("OK") ||
btnId === "btn_ok" ||
btnHandler === "ok" ||
btnHandler === "confirm"
) {
confirmButton = btn;
log(
`✅ 找到模态框确定按钮 (${btnText || btnId})`,
"info",
courseCode,
);
break;
}
}
if (confirmButton) break;
}
}
// 方法2: 直接查找带有特定ID的确定按钮
if (!confirmButton) {
confirmButton = document.querySelector(
'#btn_ok, button[data-bb-handler="ok"], button[data-bb-handler="confirm"]',
);
if (confirmButton) {
log(`✅ 通过ID找到确定按钮`, "info", courseCode);
}
}
// 方法3: 查找所有可见的确定按钮(最后备选)
if (!confirmButton) {
const allButtons = document.querySelectorAll(
'button, input[type="button"], a.btn',
);
for (let btn of allButtons) {
const text = btn.textContent.trim();
// 检查按钮是否可见
const style = window.getComputedStyle(btn);
const isVisible =
style.display !== "none" &&
style.visibility !== "hidden" &&
btn.offsetParent !== null;
if (
isVisible &&
(text === "确定" || text === "确 定" || text.includes("确定"))
) {
confirmButton = btn;
log(`✅ 找到可见的确定按钮`, "info", courseCode);
break;
}
}
}
if (confirmButton) {
log(`正在点击确定按钮...`, "info", courseCode);
confirmButton.click();
// 等待退选操作完成
setTimeout(() => {
log(`✅ 已确认退选课程 ${courseCode}`, "success", courseCode);
resolve(true);
}, 1500);
} else {
log(`❌ 未找到退选确认按钮`, "error", courseCode);
resolve(false);
}
}, 800); // 增加等待时间,确保模态框完全加载
} catch (error) {
log(`退选课程失败: ${error.message}`, "error", courseCode);
resolve(false);
}
});
}
// 尝试选择教学班
function selectTeachingClass(teachingClass) {
if (!teachingClass || !teachingClass.row) return false;
const courseCode = teachingClass.courseCode;
const classId = teachingClass.info.id;
const state = getCourseState(courseCode);
// 检查是否已经因时间冲突被跳过
if (state.conflicted.has(classId)) {
log(
`教学班 ${teachingClass.info.className} 已知时间冲突,跳过`,
"warning",
courseCode,
);
return false;
}
try {
log(
`尝试选择教学班: ${teachingClass.info.className} (${teachingClass.info.teacher})`,
"info",
courseCode,