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
| import time import random import os import json import requests from colorama import Fore, Style, init from pathlib import Path
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.chrome.service import Service import winsound
init(autoreset=True)
USERNAME = "学号/用户名" PASSWORD = "密码"
LOGIN_URL = "https://cas.s.zzu.edu.cn/cas/s/login?service=https://jwxt.zzu.edu.cn/student/sso/login" COURSE_HOME_URL = "https://jwxt.zzu.edu.cn/student/home" COURSE_TURNS_URL = "https://jwxt.zzu.edu.cn/course-selection/#/course-select/turns" TURN_SELECT_TARGETS = { "1": { "turn_id": 选课轮次ID_1, "url": "https://jwxt.zzu.edu.cn/course-selection/#/course-select/你的学生ID/turn/选课轮次ID_1/select", "label": "选项一", "lessons": [目标课程ID_1] }, "2": { "turn_id": 选课轮次ID_2, "url": "https://jwxt.zzu.edu.cn/course-selection/#/course-select/你的学生ID/turn/选课轮次ID_2/select", "label": "选项二", "lessons": [] } }
KEEPALIVE_INTERVAL = 20
SESSION_REFRESH_SECONDS = 4 * 60 + 30
def banner(): print(Fore.CYAN + Style.BRIGHT + """ ╔════════════════════════════════╗ ║ ZZU Course Grabber ║ ║ v1.2 ║ ╚════════════════════════════════╝ """)
def play_success_sound():
try: winsound.MessageBeep()
for _ in range(2): time.sleep(0.2) winsound.MessageBeep()
except: pass
def choose_mode():
print(Fore.YELLOW + "请选择运行模式:\n")
print(Fore.GREEN + " 1) 预览模式") print(Fore.BLUE + " 2) 捡漏模式") print(Fore.RED + " 3) 火力全开")
print()
mode = input("> ").strip()
if mode.lower() == "zzutest": return "test"
if mode.lower() == "zzukeepalive": return "keepalive"
if mode not in ["1", "2", "3"]: print(Fore.RED + "输入错误,默认进入预览模式") return "1"
return mode
def input_params(mode):
student_id = int(input("student_id: "))
if mode in ["1", "test"]: return student_id, []
lessons = input("课程ID(多个逗号分隔): ")
lesson_list = [int(x) for x in lessons.split(",")]
return student_id, lesson_list
def log(level, message):
now = time.strftime("%H:%M:%S")
colors = { "INFO": Fore.CYAN, "MODE": Fore.MAGENTA, "TRY": Fore.BLUE, "FULL": Fore.YELLOW, "SUCCESS": Fore.GREEN, "ERROR": Fore.RED }
color = colors.get(level, Fore.WHITE)
print(f"{color}[{now}] {level:<7} {message}")
def safe_click(driver, element):
try: element.click() return True except Exception: try: driver.execute_script("arguments[0].click();", element) return True except Exception: try: ActionChains(driver).move_to_element(element).click().perform() return True except Exception: return False
def first_available(driver, locators, timeout=8, clickable=False):
last_error = None deadline = time.monotonic() + timeout
for by, value in locators: try: remaining = deadline - time.monotonic() if remaining <= 0: break
wait = WebDriverWait(driver, remaining) condition = ( EC.element_to_be_clickable if clickable else EC.presence_of_element_located ) return wait.until(condition((by, value))) except Exception as exc: last_error = exc
if last_error: raise last_error
raise TimeoutError("no locator matched")
def text_of(element):
try: return " ".join(element.text.split()) except Exception: return ""
def unique_preserve(items):
seen = set() out = []
for item in items: if item and item not in seen: seen.add(item) out.append(item)
return out
def choose_turn_target():
print() print(Fore.YELLOW + "请选择进入的选课页:") print(Fore.GREEN + " 1) 进入 183") print(Fore.BLUE + " 2) 进入 221") print()
choice = input("> ").strip()
if choice not in TURN_SELECT_TARGETS: print(Fore.RED + "输入错误,默认进入 183") return "1"
return choice
def resolve_lessons_for_target(choice):
target = TURN_SELECT_TARGETS.get(str(choice), {}) lessons = target.get("lessons") or []
if lessons: return lessons
lessons_input = input("课程ID(多个逗号分隔): ").strip() if not lessons_input: return []
return [int(x) for x in lessons_input.split(",") if x.strip()]
def build_driver(headless=False):
options = webdriver.ChromeOptions() options.add_argument("--start-maximized") options.add_argument("--disable-gpu") options.add_argument("--no-sandbox") if headless: options.add_argument("--headless=new") options.add_argument("--window-size=1440,1000") options.set_capability("goog:loggingPrefs", {"performance": "ALL"})
original_path = os.environ.get("PATH", "") filtered_parts = []
for part in original_path.split(os.pathsep): if not part: continue
candidate = Path(part) / "chromedriver.exe" if candidate.exists(): continue
filtered_parts.append(part)
os.environ["PATH"] = os.pathsep.join(filtered_parts)
try: log("INFO", "启动浏览器,已忽略旧版 chromedriver") cached_drivers = sorted( Path.home().glob( ".cache/selenium/chromedriver/win64/*/chromedriver.exe" ), key=lambda path: path.stat().st_mtime, reverse=True )
if cached_drivers: driver_path = cached_drivers[0] log("INFO", f"使用本地 ChromeDriver 缓存: {driver_path.parent.name}") return webdriver.Chrome( service=Service(str(driver_path)), options=options )
return webdriver.Chrome(service=Service(), options=options) finally: os.environ["PATH"] = original_path
def run_login_flow(driver, student_id):
course_locators = [ (By.XPATH, "//div[contains(@class,'shortcut-item') and .//*[contains(text(),'选课')]]"), (By.XPATH, "//div[contains(@class,'shortcut') and .//*[contains(text(),'选课')]]"), (By.XPATH, "//button[contains(.,'选课')]"), (By.XPATH, "//a[contains(.,'选课')]"), (By.XPATH, "//*[contains(text(),'选课') and (self::div or self::button or self::a)]"), ]
try:
driver.get(LOGIN_URL)
log("INFO", "登录中...")
try: course_icon = first_available( driver, course_locators, timeout=4, clickable=True ) log("INFO", "CAS 会话仍有效,跳过重复输入账号密码") except Exception: username_input = first_available( driver, [ (By.CSS_SELECTOR, "input[placeholder='请输入学号/工号']"), (By.ID, "yhm"), (By.NAME, "username"), (By.CSS_SELECTOR, "input[type='text']"), ], timeout=15, clickable=True ) username_input.clear() username_input.send_keys(USERNAME)
password_input = first_available( driver, [ (By.CSS_SELECTOR, "input[placeholder='请输入统一身份认证密码']"), (By.ID, "mm"), (By.NAME, "password"), (By.CSS_SELECTOR, "input[type='password']"), ], timeout=15, clickable=True ) password_input.clear() password_input.send_keys(PASSWORD)
login_button = first_available( driver, [ (By.CLASS_NAME, "login-btn"), (By.ID, "dl"), (By.XPATH, "//button[contains(.,'登录')]"), ], timeout=15, clickable=True ) safe_click(driver, login_button)
log("INFO", "进入选课入口")
course_icon = first_available( driver, course_locators, timeout=15, clickable=True )
safe_click(driver, course_icon)
return True
except Exception as e:
log("ERROR", f"登录流程错误 {e}")
return False
def open_turns_preview(driver):
log("INFO", "进入 turns 预览页")
candidates = [ COURSE_TURNS_URL, COURSE_HOME_URL, ]
for url in candidates: try: driver.get(url) time.sleep(1.2) except Exception: continue
try: if "course-select/turns" in driver.current_url: log("INFO", f"当前页面: {driver.current_url}") return True except Exception: pass
try: driver.execute_script(f"window.location.href = '{COURSE_TURNS_URL}';") time.sleep(1.2) if "course-select/turns" in driver.current_url: log("INFO", f"当前页面: {driver.current_url}") return True except Exception: pass
log("ERROR", "未能进入 turns 预览页") return False
def click_select_entry(driver, target):
turn_id = str(target["turn_id"]) terms = unique_preserve([ turn_id, target.get("label", ""), target.get("url", ""), ])
locator_sets = [ (By.XPATH, f"//button[contains(.,'{turn_id}')]"), (By.XPATH, f"//a[contains(.,'{turn_id}')]"), (By.XPATH, f"//div[contains(.,'{turn_id}')]"), (By.XPATH, f"//*[@role='button' and contains(.,'{turn_id}')]"), (By.XPATH, f"//*[contains(@href,'{turn_id}')]"), (By.XPATH, f"//*[contains(@onclick,'{turn_id}')]"), ]
for by, value in locator_sets: try: elements = driver.find_elements(by, value) except Exception: continue
for element in elements: txt = " ".join( [ text_of(element), element.get_attribute("aria-label") or "", element.get_attribute("title") or "", element.get_attribute("href") or "", element.get_attribute("onclick") or "", ] ) if any(term and term in txt for term in terms): if safe_click(driver, element): return True
try: clicked = driver.execute_script( """ const terms = arguments[0]; const nodes = Array.from(document.querySelectorAll('button,a,[role="button"],div')); for (const node of nodes) { const text = (node.innerText || node.textContent || '').trim(); const aria = node.getAttribute('aria-label') || ''; const title = node.getAttribute('title') || ''; const href = node.getAttribute('href') || ''; const onclick = node.getAttribute('onclick') || ''; const haystack = [text, aria, title, href, onclick].join(' '); if (terms.some(t => t && haystack.includes(t))) { node.click(); return true; } } return false; """, terms ) return bool(clicked) except Exception: return False
def open_select_page(driver, choice):
target = TURN_SELECT_TARGETS.get(str(choice))
if not target: log("ERROR", f"未知的选课页选项: {choice}") return False
target_url = target["url"] turn_id = target["turn_id"]
log("INFO", f"进入 select 页: {turn_id}")
for attempt in range(1, 4): try: if attempt == 1: click_select_entry(driver, target) time.sleep(1.5)
driver.get(target_url)
WebDriverWait(driver, 15).until( lambda d: str(turn_id) in d.current_url and "select" in d.current_url )
log("INFO", f"当前页面: {driver.current_url}") return True except Exception: try: current_url = driver.current_url log("INFO", f"第 {attempt} 次进入失败,当前页面: {current_url}") except Exception: pass
time.sleep(1.5)
log("ERROR", f"未能进入 select 页: {turn_id}") return False
def preview_turn_options(driver):
wait = WebDriverWait(driver, 20)
log("INFO", "等待预览项加载")
wait.until( lambda d: "course-select/turns" in d.current_url )
time.sleep(1)
raw_candidates = []
locator_sets = [ (By.XPATH, "//button"), (By.XPATH, "//a"), (By.XPATH, "//*[@role='button']"), (By.XPATH, "//*[contains(@class,'card') or contains(@class,'Card')]"), (By.XPATH, "//*[contains(@class,'item') or contains(@class,'Item')]"), ]
for by, value in locator_sets: try: elements = driver.find_elements(by, value) except Exception: continue
for element in elements: txt = text_of(element) if not txt: continue if len(txt) > 120: continue if any(skip in txt for skip in ["返回", "首页", "退出", "刷新", "搜索"]): continue raw_candidates.append(txt)
options = unique_preserve(raw_candidates)
if not options: page_text = driver.page_source if "course-select/turns" in page_text: log("INFO", "页面已加载,但未提取到显式选项") print(Fore.YELLOW + "请手动确认页面上的三个可选项是否已渲染。") return []
preview = options[:3]
print() print(Fore.CYAN + Style.BRIGHT + "预览到的可选项:") for idx, item in enumerate(preview, 1): print(Fore.WHITE + f"{idx}. {item}")
if len(preview) < 3: print(Fore.YELLOW + f"当前只提取到 {len(preview)} 项,页面可能还在加载或结构已变化。")
return preview
def get_auth_assets(driver): try: cookies = driver.get_cookies()
cookie_str = "; ".join([f"{c['name']}={c['value']}" for c in cookies])
token = None
for c in cookies: if "token" in c["name"].lower(): token = c["value"]
if not token: for key in ["token", "TOKEN", "authToken", "Authorization"]: token = driver.execute_script( f"return window.localStorage.getItem('{key}');" ) if token: break
if not token: for key in ["token", "TOKEN", "authToken", "Authorization"]: token = driver.execute_script( f"return window.sessionStorage.getItem('{key}');" ) if token: break
return token, cookie_str except Exception as exc: log("ERROR", f"无法读取浏览器会话: {exc}") return None, None
def read_std_count_network(driver): """Read the select page's own std-count request and response events."""
latest_url = None latest_status = None observed = False
try: entries = driver.get_log("performance") except Exception: return None, None, False
for entry in entries: try: message = json.loads(entry["message"])["message"] except Exception: continue
method = message.get("method") params = message.get("params", {})
if method == "Network.requestWillBeSent": request = params.get("request", {}) url = request.get("url", "") if "std-count" in url.lower(): latest_url = url observed = True
elif method == "Network.responseReceived": response = params.get("response", {}) url = response.get("url", "") if "std-count" in url.lower(): latest_url = url latest_status = response.get("status") observed = True
return latest_url, latest_status, observed
def send_keepalive(session, token, cookies, std_count_url):
if not std_count_url: return None
headers = { "authorization": token or "", "cookie": cookies or "", "user-agent": "Mozilla/5.0", "origin": "https://jwxt.zzu.edu.cn", "referer": "https://jwxt.zzu.edu.cn/course-selection/" }
try: response = session.get(std_count_url, headers=headers, timeout=5) return response.status_code except requests.RequestException: return None
def restore_session(driver, student_id, choice):
log("INFO", "会话即将失效,重新登录并恢复选课页面")
if not run_login_flow(driver, student_id): log("ERROR", "重新登录失败") return None, None
if not open_select_page(driver, choice): log("ERROR", "重新登录后未能恢复 select 页") return None, None
token, cookies = get_auth_assets(driver) if not token: log("ERROR", "恢复后未能重新提取 token") return None, None
log("INFO", "会话恢复成功") return token, cookies
def api_request(session, token, cookies, student_id, turn_id, lesson_id):
api = "https://jwxt.zzu.edu.cn/course-selection-api/api/v1/student/course-select"
headers = { "authorization": token, "cookie": cookies, "content-type": "application/json", "user-agent": "Mozilla/5.0", "origin": "https://jwxt.zzu.edu.cn", "referer": "https://jwxt.zzu.edu.cn/course-selection/" }
payload = { "studentAssoc": student_id, "courseSelectTurnAssoc": turn_id, "coursePackAssoc": None, "requestMiddleDtos": [ {"lessonAssoc": lesson_id, "virtualCost": None} ] }
start = time.time()
try:
r = session.post( f"{api}/add-request", json=payload, headers=headers, timeout=3 )
if r.status_code == 401: return False, "RELOGIN", 0
req_id = r.json().get("data")
if req_id:
time.sleep(0.15)
r2 = session.get( f"{api}/add-drop-response/{student_id}/{req_id}", headers=headers, timeout=3 )
if r2.status_code == 401: return False, "RELOGIN", 0
latency = int((time.time() - start) * 1000)
data = r2.json().get("data", {})
success = data.get("success", False)
err = data.get("errorMessage")
msg = err.get("text") if err else ("成功" if success else "排队")
return success, msg, latency
except: return False, "网络异常", 0
return False, "未知", 0
def mode_runtime(driver, session, token, cookies, student_id, choice, turn_id, lessons):
attempts = 0
start_time = time.time() last_keepalive = time.time() last_session_refresh = time.time() last_browser_heartbeat = time.time() std_count_url = None
if lessons: log("MODE", f"选课模式启动,目标课程: {lessons}") else: log("MODE", "预览模式启动,仅监听 std-count,不发送选课请求")
while True: try: observed_url, observed_status, observed = read_std_count_network(driver) driver.current_url except Exception as exc: log("ERROR", f"浏览器连接已断开,停止运行: {exc}") return
if observed_url: if observed_url != std_count_url: log("INFO", "已捕获选课页 std-count 心跳地址") std_count_url = observed_url if observed: last_browser_heartbeat = time.time()
if observed_status == 401: token, cookies = restore_session(driver, student_id, choice) if not token: time.sleep(5) continue session = requests.Session() last_keepalive = time.time() last_session_refresh = time.time() continue
now = time.time() if ( now - last_keepalive >= KEEPALIVE_INTERVAL and now - last_browser_heartbeat >= KEEPALIVE_INTERVAL + 5 and std_count_url ): status = send_keepalive(session, token, cookies, std_count_url) last_keepalive = now
if status == 401: token, cookies = restore_session(driver, student_id, choice) if not token: time.sleep(5) continue session = requests.Session() last_keepalive = time.time() last_session_refresh = time.time() continue
if status == 200: log("INFO", "std-count 保活请求正常")
if now - last_session_refresh >= SESSION_REFRESH_SECONDS: token, cookies = restore_session(driver, student_id, choice) if not token: time.sleep(5) continue session = requests.Session() last_keepalive = time.time() last_session_refresh = time.time() continue
for lesson in lessons:
attempts += 1
success, msg, latency = api_request( session, token, cookies, student_id, turn_id, lesson )
now = time.time()
qps = attempts / (now - start_time)
log( "TRY", f"课程:{lesson} | 第{attempts}次 | QPS:{qps:.1f} | 延迟:{latency}ms" )
if "满" in msg: log("FULL", msg)
if msg == "RELOGIN": token, cookies = restore_session(driver, student_id, choice) if not token: time.sleep(5) continue session = requests.Session() last_keepalive = time.time() last_session_refresh = time.time() break
if success: play_success_sound()
print("\n") print(Fore.GREEN + Style.BRIGHT) print("=================================") print(" 🎉 抢课成功 🎉") print("=================================") print(Fore.WHITE + f"课程: {lesson}") print("时间:", time.strftime("%H:%M:%S"))
return
time.sleep(random.uniform(0.3, 0.6))
def mode_test():
print() print(Fore.MAGENTA + "进入隐藏测试模式") print()
for i in range(5):
ts = time.strftime("%H:%M:%S")
print( f"[{ts}] " f"{Fore.CYAN}课程:目标课程ID " f"{Fore.BLUE}第{i+1}次 " f"{Fore.YELLOW}状态:教学班人数已满" )
time.sleep(0.5)
print() print(Fore.GREEN + Style.BRIGHT) play_success_sound() print("=================================") print(" 🎉 抢课成功 🎉") print("=================================") print(Fore.WHITE + "课程: 目标课程ID") print("时间:", time.strftime("%H:%M:%S"))
def main():
banner()
mode = choose_mode()
student_id = int(input("student_id: "))
driver = build_driver(headless=(mode == "keepalive"))
if not run_login_flow(driver, student_id): return
if mode == "test": mode_test() return
select_choice = choose_turn_target() turn_id = TURN_SELECT_TARGETS[select_choice]["turn_id"]
if not open_select_page(driver, select_choice): return
if mode in ["keepalive", "1"]: lessons = [] if mode == "1": log("INFO", "已进入 select 页,保持运行并监听保活请求") elif mode == "2": lessons = resolve_lessons_for_target(select_choice) else: lessons = []
session = requests.Session() token, cookies = get_auth_assets(driver)
if mode in ["keepalive", "1", "2"]: mode_runtime( driver, session, token, cookies, student_id, select_choice, turn_id, lessons ) return
session = requests.Session()
token, cookies = get_auth_assets(driver)
print(Fore.RED + "火力全开模式开发中...")
if __name__ == "__main__":
try: main() except KeyboardInterrupt: print(Fore.RED + "\n脚本已停止")
|