1007 lines
42 KiB
Python
1007 lines
42 KiB
Python
#!/usr/bin/env python
|
||
# -*- coding: utf-8 -*-
|
||
"""
|
||
教务系统课表查询 API 模块
|
||
|
||
接口来源:逆向 cxkbazc_cxXskbcx.js / kbcx_xskbcx.js
|
||
|
||
使用方式:
|
||
from app.kbcx_api import KbcxAPI
|
||
|
||
api = KbcxAPI("253051601132")
|
||
|
||
# 获取当前学年学期(从页面预设变量读取)
|
||
meta = api.get_semester_meta()
|
||
# -> {"xnm": "2025", "xqm": "12", "xxdm": "14438", "sfbczc": "1", "xqh_id": "..."}
|
||
|
||
# 获取周次列表
|
||
weeks = api.get_week_list(xnm="2025", xqm="12")
|
||
# -> [{"zs": "1", "zcrq": "2025-09-01"}, ...]
|
||
|
||
# 按周查课表(kblx=1)
|
||
kb = api.get_timetable(xnm="2025", xqm="12", zs="1", kblx="1")
|
||
|
||
# 全学期课表(kblx=2,无需 zs)
|
||
kb = api.get_timetable(xnm="2025", xqm="12", kblx="2")
|
||
|
||
# 查询他人课表(xh 指定学号)
|
||
kb = api.get_timetable(xnm="2025", xqm="12", kblx="2", xh="202212110110")
|
||
|
||
# 格式化课表(按周过滤 + 带上下课时间)
|
||
table = api.format_timetable(kb, week=3)
|
||
api.print_timetable(table)
|
||
|
||
# 获取日时段列表(课表行结构)
|
||
rsd = api.get_rsd_list(xnm="2025", xqm="12", xqh_id="...")
|
||
|
||
# 获取节次上下课时间
|
||
jc = api.get_jc_times(xnm="2025", xqm="12", xqh_id="...")
|
||
|
||
所有返回值均为 JSON 兼容的 dict/list,出错时抛 RuntimeError。
|
||
"""
|
||
|
||
import json
|
||
import re
|
||
import logging
|
||
from datetime import datetime, timezone, timedelta
|
||
from pathlib import Path
|
||
from typing import Dict, List, Optional, Any, Tuple
|
||
|
||
import requests
|
||
|
||
|
||
logger = logging.getLogger(__name__)
|
||
|
||
|
||
# ── 路径 & 常量 ──────────────────────────────────────────────
|
||
from app.settings import SESSION_DIR
|
||
from app.url_manager import get_base_url
|
||
|
||
def _url(path: str) -> str:
|
||
"""拼接当前 BASE_URL + 路径"""
|
||
return get_base_url() + path
|
||
|
||
# 页面入口(GET,带必要参数,服务端会渲染 hidden 变量)
|
||
INDEX_URL_WEEKLY = lambda: _url("/kbcx/xskbcxZccx_cxXskbcxIndex.html?gnmkdm=N2154&layout=default")
|
||
INDEX_URL_FULL = lambda: _url("/kbcx/xskbcx_cxXskbcxIndex.html?gnmkdm=N2151&layout=default")
|
||
|
||
# 接口地址
|
||
API_WEEK_LIST = lambda: _url("/kbcx/xskbcxZccx_cxZcByXnxq.html")
|
||
API_TIMETABLE = lambda: _url("/kbcx/xskbcxMobile_cxXsKb.html")
|
||
API_RSD = lambda: _url("/kbcx/xskbcxMobile_cxRsd.html")
|
||
API_JC_TIMES = lambda: _url("/jzgl/skxxMobile_cxRsdjc.html")
|
||
|
||
# 网页版接口(个人课表查询页 gnmkdm=N2151 所用)。
|
||
# 部分学校(如青岛城市学院)的 Mobile 接口返回空 kbList,必须走网页版接口;
|
||
# 网页版课表查询按钮虽挂了滑块验证码(zfcaptcha),但页面初始加载的接口本身不校验验证码。
|
||
API_TIMETABLE_WEB = lambda: _url("/kbcx/xskbcx_cxXsgrkb.html") + "?gnmkdm=N2151"
|
||
API_JC_TIMES_WEB = lambda: _url("/kbcx/xskbcx_cxRjc.html") + "?gnmkdm=N2151"
|
||
|
||
# 课表空闲热度图(BestSimpleIndex)
|
||
API_HEATMAP = lambda: _url("/kbcx/xskbcx_cxXskbBestSimpleIndex.html")
|
||
|
||
|
||
# ── KbcxAPI 主类 ─────────────────────────────────────────────
|
||
class KbcxAPI:
|
||
"""
|
||
教务系统课表查询 API。
|
||
|
||
核心流程:
|
||
1. get_semester_meta() —— GET 按周课表首页,解析服务端预渲染的 xnm/xqm/xxdm 等参数
|
||
2. get_week_list() —— POST cxZcByXnxq,获取本学期周次列表
|
||
3. get_timetable() —— POST cxXsKb,查询课表数据(按周 or 全学期)
|
||
4. get_rsd_list() —— POST cxRsd,获取日时段列表(渲染课表行用)
|
||
5. get_jc_times() —— POST cxRsdjc,获取各节次上下课时间
|
||
"""
|
||
|
||
def __init__(self, username: str):
|
||
self.username = username
|
||
self.session = self._load_session()
|
||
self._meta_cache: Optional[Dict] = None # get_semester_meta 缓存
|
||
|
||
# ── session 加载 ──────────────────────────────────────────
|
||
|
||
def _load_session(self) -> requests.Session:
|
||
from app.session_manager import SessionManager
|
||
sf = SessionManager.get_session_file(self.username)
|
||
if not sf.exists():
|
||
raise FileNotFoundError(
|
||
f"session 文件不存在: {sf}\n"
|
||
f"请先运行: python app/update_session.py -u {self.username}"
|
||
)
|
||
data = json.loads(sf.read_text(encoding="utf-8"))
|
||
sess = requests.Session()
|
||
sess.cookies.update(data.get("cookies", {}))
|
||
sess.headers.update({
|
||
"User-Agent": (
|
||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
||
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
||
"Chrome/131.0.0.0 Safari/537.36"
|
||
),
|
||
"Referer": INDEX_URL_WEEKLY(),
|
||
"X-Requested-With": "XMLHttpRequest",
|
||
})
|
||
return sess
|
||
|
||
# ── 通用工具 ──────────────────────────────────────────────
|
||
|
||
def _kbcx_source(self) -> str:
|
||
"""当前账号所属学校配置的课表接口来源(auto/web/mobile)"""
|
||
try:
|
||
from app.school_manager import kbcx_source, school_for_username
|
||
from app.url_manager import current_school_id
|
||
school_id = current_school_id() or school_for_username(self.username)
|
||
return kbcx_source(school_id)
|
||
except Exception:
|
||
return 'auto'
|
||
|
||
def _post_json(self, url: str, data: Dict) -> Any:
|
||
"""POST 表单,自动解析 JSON,失败时抛 RuntimeError。"""
|
||
r = self.session.post(url, data=data, timeout=15)
|
||
r.raise_for_status()
|
||
|
||
try:
|
||
return r.json()
|
||
except Exception:
|
||
# 如果返回的是 HTML 错误页面,将完整 HTML 内容包含在错误信息中
|
||
if r.text.strip().startswith('<!doctype html>') or r.text.strip().startswith('<html'):
|
||
if '无功能权限' in r.text:
|
||
raise RuntimeError("教务系统密码已到期(无功能权限),需重置密码")
|
||
raise RuntimeError(
|
||
f"接口返回 HTML 错误页面\n"
|
||
f"URL: {url}\n"
|
||
f"状态码: {r.status_code}\n"
|
||
f"完整内容:\n{r.text}"
|
||
)
|
||
raise RuntimeError(
|
||
f"接口返回非 JSON\n"
|
||
f"URL: {url}\n"
|
||
f"状态码: {r.status_code}\n"
|
||
f"解析错误\n"
|
||
f"内容: {r.text[:500]}"
|
||
)
|
||
|
||
@staticmethod
|
||
def _get_hidden(html: str, field_id: str, default: str = "") -> str:
|
||
"""
|
||
从 HTML 中提取 hidden input 的 value。
|
||
兼容:id/name 属性乱序、属性等号旁有空格、单双引号混用。
|
||
"""
|
||
# 先把 HTML 中多余空白压缩,方便正则匹配(仅在 input 标签范围内)
|
||
# 统一匹配:在同一个 <input ...> 标签内,同时含 id/name=field_id 和 value=xxx
|
||
field_escaped = re.escape(field_id)
|
||
# 先尝试直接按 id 或 name 找(允许等号旁边有空格)
|
||
patterns = [
|
||
# id = "field_id" ... value = "xxx"
|
||
r'id\s*=\s*["\']' + field_escaped + r'["\'][^>]*?value\s*=\s*["\']([^"\']*)["\']',
|
||
# value = "xxx" ... id = "field_id"
|
||
r'value\s*=\s*["\']([^"\']*)["\'][^>]*?id\s*=\s*["\']' + field_escaped + r'["\']',
|
||
# name = "field_id" ... value = "xxx"
|
||
r'name\s*=\s*["\']' + field_escaped + r'["\'][^>]*?value\s*=\s*["\']([^"\']*)["\']',
|
||
# value = "xxx" ... name = "field_id"
|
||
r'value\s*=\s*["\']([^"\']*)["\'][^>]*?name\s*=\s*["\']' + field_escaped + r'["\']',
|
||
]
|
||
for pat in patterns:
|
||
m = re.search(pat, html)
|
||
if m:
|
||
return m.group(1)
|
||
return default
|
||
|
||
@staticmethod
|
||
def _get_js_var(html: str, var_name: str, default: str = "") -> str:
|
||
"""从页面 JS 片段中提取 `var xxx = "yyy"` 或 `xxx: "yyy"` 形式的变量值。"""
|
||
for pat in [
|
||
r'var\s+' + re.escape(var_name) + r'\s*=\s*["\']([^"\']*)["\']',
|
||
r'"' + re.escape(var_name) + r'"\s*:\s*["\']([^"\']*)["\']',
|
||
r"'" + re.escape(var_name) + r"'\s*:\s*[\"']([^\"']*)[\"']",
|
||
]:
|
||
m = re.search(pat, html)
|
||
if m:
|
||
return m.group(1)
|
||
return default
|
||
|
||
# ── 步骤 1:解析首页预渲染参数 ────────────────────────────
|
||
|
||
def get_semester_meta(self, use_cache: bool = True) -> Dict[str, str]:
|
||
"""
|
||
GET 按周课表首页,提取服务端渲染的学年/学期等基础参数。
|
||
|
||
返回字段:
|
||
xnm 学年(如 "2025")
|
||
xqm 学期("3"=第一学期,"12"=第二学期)
|
||
xxdm 学校代码(SDMU = "14438")
|
||
sfbczc 是否完成缴费注册("0"=未缴费,无法查课表)
|
||
xqh_id 校区 ID(用于查询日时段/节次时间)
|
||
"""
|
||
if use_cache and self._meta_cache:
|
||
return self._meta_cache
|
||
|
||
r = self.session.get(INDEX_URL_WEEKLY(), allow_redirects=False, timeout=15)
|
||
if r.status_code == 302:
|
||
raise RuntimeError("session 已过期,请重新登录(运行 python app/update_session.py)")
|
||
r.raise_for_status()
|
||
|
||
html = r.text
|
||
|
||
# xnm:id="xnm_hide" 或 name="xnm"
|
||
xnm = self._get_hidden(html, "xnm_hide") or self._get_hidden(html, "xnm")
|
||
# xqm:id="xqm_hide" 或 name="xqm"
|
||
xqm = self._get_hidden(html, "xqm_hide") or self._get_hidden(html, "xqm")
|
||
# xxdm:id="hidxxdm" 或 name="xxdm" 或 id="xxdm"
|
||
xxdm = (
|
||
self._get_hidden(html, "hidxxdm")
|
||
or self._get_hidden(html, "xxdm")
|
||
)
|
||
# sfbczc:id="sfbczc"
|
||
sfbczc = self._get_hidden(html, "sfbczc")
|
||
# xqh_id:首页可能没有,留空(从课表数据里拿)
|
||
xqh_id = self._get_hidden(html, "xqh_id")
|
||
|
||
# 解析学年/学期下拉框的所有选项
|
||
xnm_options = []
|
||
xqm_options = []
|
||
xnm_select = re.search(r'<select[^>]*id="xnm"[^>]*>(.*?)</select>', html, re.DOTALL)
|
||
if xnm_select:
|
||
for m in re.finditer(r'<option[^>]*value="(\d+)"[^>]*>(.*?)</option>', xnm_select.group(1)):
|
||
xnm_options.append({'value': m.group(1), 'label': m.group(2).strip()})
|
||
xqm_select = re.search(r'<select[^>]*id="xqm"[^>]*>(.*?)</select>', html, re.DOTALL)
|
||
if xqm_select:
|
||
for m in re.finditer(r'<option[^>]*value="([^"]+)"[^>]*>(.*?)</option>', xqm_select.group(1)):
|
||
xqm_options.append({'value': m.group(1), 'label': m.group(2).strip()})
|
||
|
||
# 最后兜底:JS 变量
|
||
if not xnm: xnm = self._get_js_var(html, "xnm")
|
||
if not xqm: xqm = self._get_js_var(html, "xqm")
|
||
if not xxdm: xxdm = self._get_js_var(html, "xxdm")
|
||
if not sfbczc: sfbczc = self._get_js_var(html, "sfbczc")
|
||
|
||
# ── 日期计算:用实际时间覆盖服务端默认学年 ──────────────
|
||
# 教务系统默认拉取最新学年(如 2026),但实际当前学年应按日期计算(8月分界):
|
||
# 当前月份 ≥ 8 → 当前学年 = 今年 (8月~12月,2026-2027学年第一学期,xnm=2026, xqm=3)
|
||
# 当前月份 < 8 → 当前学年 = 去年 (1月~7月,2025-2026学年第二学期,xnm=2025, xqm=12)
|
||
BJ_TZ = timezone(timedelta(hours=8))
|
||
now_bj = datetime.now(BJ_TZ)
|
||
if now_bj.month >= 8:
|
||
computed_xnm = str(now_bj.year)
|
||
else:
|
||
computed_xnm = str(now_bj.year - 1)
|
||
if xnm != computed_xnm:
|
||
logger.info(
|
||
f"学年覆盖: 服务端默认 xnm={xnm},"
|
||
f"按当前日期({now_bj.strftime('%Y-%m-%d %H:%M')})"
|
||
f"计算为 xnm={computed_xnm},已自动修正"
|
||
)
|
||
xnm = computed_xnm
|
||
# 自动推断学期:8月~12月(秋季)=第一学期(xqm=3),1月~7月(春季+暑假)=第二学期(xqm=12)
|
||
xqm = "3" if now_bj.month >= 8 else "12"
|
||
|
||
meta = {
|
||
"xnm": xnm,
|
||
"xqm": xqm,
|
||
"xxdm": xxdm,
|
||
"sfbczc": sfbczc,
|
||
"xqh_id": xqh_id,
|
||
"xnm_options": xnm_options,
|
||
"xqm_options": xqm_options,
|
||
}
|
||
self._meta_cache = meta
|
||
return meta
|
||
|
||
# ── 步骤 2:获取周次列表 ──────────────────────────────────
|
||
|
||
def get_week_list(self, xnm: str, xqm: str) -> List[Dict]:
|
||
"""
|
||
获取本学期所有周次。
|
||
|
||
参数:
|
||
xnm 学年(如 "2025")
|
||
xqm 学期("12" 或 "3")
|
||
|
||
返回(列表,每项一周):
|
||
zs 周次编号(字符串,如 "1"),用于 get_timetable 的 zs 参数
|
||
zcrq 该周起始日期(如 "2025-09-01")
|
||
"""
|
||
result = self._post_json(API_WEEK_LIST(), {"xnm": xnm, "xqm": xqm})
|
||
# 接口直接返回列表
|
||
if isinstance(result, list):
|
||
return result
|
||
# 有些版本套了一层 {"items": [...]}
|
||
if isinstance(result, dict):
|
||
for key in ("items", "data", "rows", "list"):
|
||
if key in result and isinstance(result[key], list):
|
||
return result[key]
|
||
return result
|
||
|
||
# ── 步骤 3:查询课表 ──────────────────────────────────────
|
||
|
||
def get_timetable(
|
||
self,
|
||
xnm: str,
|
||
xqm: str,
|
||
kblx: str = "1",
|
||
zs: str = "",
|
||
xh: str = "",
|
||
) -> Dict:
|
||
"""
|
||
查询课表数据(主接口)。
|
||
|
||
参数:
|
||
xnm 学年(如 "2025")
|
||
xqm 学期("12" 或 "3")
|
||
kblx 课表类型:"1"=按周,"2"=全学期
|
||
zs 周次(kblx="1" 时必填,值来自 get_week_list 的 zs 字段)
|
||
xh 学号(为空时查当前登录用户)
|
||
|
||
返回 dict,关键字段:
|
||
kbList[] 课程列表,每项含:
|
||
kcmc 课程名
|
||
xm 教师姓名
|
||
jxbmc 教学班名称
|
||
cdmc 上课地点(教室)
|
||
xqmc 校区名
|
||
xqj 星期(1-7,1=周一)
|
||
jcor 节次范围(如 "1-2")
|
||
zcd 周次描述(如 "1-18周")
|
||
xnm 学年
|
||
xqm 学期
|
||
xqh_id 校区 ID
|
||
cdbh 教室编号
|
||
sjkList[] 实践课列表(同 kbList 结构)
|
||
xsxx 学生基本信息 dict
|
||
kblx 课表类型(回显)
|
||
xkkg 选课是否开放(bool)
|
||
jfckbkg 缴费后才能查看开关(bool)
|
||
rqazcList 日期-星期对照 [{xqj, rq}, ...]
|
||
qsxqj 起始星期(通常 "1","7" 表示周日在前)
|
||
zckbsfxssj 是否显示上下课时间("1"=显示)
|
||
"""
|
||
payload: Dict[str, str] = {
|
||
"xnm": xnm,
|
||
"xqm": xqm,
|
||
"kblx": kblx,
|
||
"doType": "app",
|
||
}
|
||
if kblx == "1" and zs:
|
||
payload["zs"] = zs
|
||
if xh:
|
||
payload["xh"] = xh
|
||
|
||
# 网页版接口(kblx 取值 "xskb",按周时带 zs,服务端会做周次过滤并返回 rqazcList)。
|
||
# 部分学校(如青岛城市学院)的 Mobile 接口无论什么参数都返回空 kbList,
|
||
# 课表来源由管理面板按学校配置:auto=网页版优先回退Mobile / web / mobile。
|
||
web_payload: Dict[str, str] = {
|
||
"xnm": xnm,
|
||
"xqm": xqm,
|
||
"kblx": "xskb",
|
||
"doType": "kdkb",
|
||
}
|
||
if kblx == "1" and zs:
|
||
web_payload["zs"] = zs
|
||
if xh:
|
||
web_payload["xh"] = xh
|
||
|
||
def _has_courses(d: Any) -> bool:
|
||
if not isinstance(d, dict):
|
||
return False
|
||
return bool(d.get("kbList") or d.get("sjkList") or d.get("jxhjkcList"))
|
||
|
||
source = self._kbcx_source()
|
||
if source == "web":
|
||
result = self._post_json(API_TIMETABLE_WEB(), web_payload)
|
||
elif source == "mobile":
|
||
result = self._post_json(API_TIMETABLE(), payload)
|
||
else:
|
||
# auto:网页版优先,失败或返回空时回退 Mobile 接口交叉验证
|
||
try:
|
||
web_result = self._post_json(API_TIMETABLE_WEB(), web_payload)
|
||
if _has_courses(web_result):
|
||
result = web_result
|
||
else:
|
||
# 网页版返回空:可能是真的没课,也可能是该校网页接口受限,
|
||
# 用 Mobile 接口交叉验证,取非空者
|
||
mobile_result = self._post_json(API_TIMETABLE(), payload)
|
||
result = mobile_result if _has_courses(mobile_result) else web_result
|
||
except Exception:
|
||
# 网页版接口不可用(无权限/返回 HTML 等),退回 Mobile 接口
|
||
result = self._post_json(API_TIMETABLE(), payload)
|
||
|
||
# 统一规范化周次描述:单双标记只作用于所在分段,
|
||
# zcd 输出为通用周数描述,并附加 zcd_weeks 确切周次列表
|
||
return self._normalize_zcd_fields(result)
|
||
|
||
# ── 步骤 4:日时段列表(课表行结构)──────────────────────
|
||
|
||
def get_rsd_list(self, xnm: str, xqm: str, xqh_id: str) -> List[Dict]:
|
||
"""
|
||
获取日时段列表,用于渲染课表的行结构。
|
||
|
||
参数:
|
||
xnm 学年
|
||
xqm 学期
|
||
xqh_id 校区 ID(从 get_semester_meta 或课表数据的 xqh_id 获取)
|
||
|
||
返回列表,每项:
|
||
rsdmc 日时段名称(如 "上午"、"下午"、"晚上")
|
||
rsdzjs 该时段节次数量(int)
|
||
"""
|
||
result = self._post_json(
|
||
API_RSD(),
|
||
{"xnm": xnm, "xqm": xqm, "xqh_id": xqh_id}
|
||
)
|
||
if isinstance(result, list):
|
||
return result
|
||
if isinstance(result, dict):
|
||
for key in ("items", "data", "rows", "list"):
|
||
if key in result and isinstance(result[key], list):
|
||
return result[key]
|
||
return result
|
||
|
||
# ── 步骤 5:节次上下课时间 ────────────────────────────────
|
||
|
||
def get_jc_times(self, xnm: str, xqm: str, xqh_id: str) -> List[Dict]:
|
||
"""
|
||
获取各节次上下课时间。
|
||
|
||
参数:
|
||
xnm 学年
|
||
xqm 学期
|
||
xqh_id 校区 ID
|
||
|
||
返回列表,每项:
|
||
jcmc 节次名称(如 "第1节")
|
||
qssj 开始时间(如 "08:00")
|
||
jssj 结束时间(如 "08:45")
|
||
rsdjcmc 所属日时段名称(如 "上午")
|
||
"""
|
||
params = {"xnm": xnm, "xqm": xqm, "xqh_id": xqh_id}
|
||
|
||
def _as_list(result: Any) -> list:
|
||
if isinstance(result, list):
|
||
return result
|
||
if isinstance(result, dict):
|
||
for key in ("items", "data", "rows", "list"):
|
||
if key in result and isinstance(result[key], list):
|
||
return result[key]
|
||
return []
|
||
|
||
source = self._kbcx_source()
|
||
if source == "web":
|
||
return _as_list(self._post_json(API_JC_TIMES_WEB(), params))
|
||
if source == "mobile":
|
||
return _as_list(self._post_json(API_JC_TIMES(), params))
|
||
|
||
# auto:网页版优先(部分学校的 Mobile 版返回空列表),空时回退 Mobile
|
||
try:
|
||
raw = _as_list(self._post_json(API_JC_TIMES_WEB(), params))
|
||
if raw:
|
||
return raw
|
||
return _as_list(self._post_json(API_JC_TIMES(), params))
|
||
except Exception:
|
||
return _as_list(self._post_json(API_JC_TIMES(), params))
|
||
|
||
# ── 便捷方法:自动获取元数据并查全学期课表 ───────────────
|
||
|
||
def get_my_timetable(self, kblx: str = "2", week: int = 0) -> Dict:
|
||
"""
|
||
便捷方法:自动从首页读取 xnm/xqm,查询当前登录用户的课表。
|
||
|
||
参数:
|
||
kblx "1"=按周,"2"=全学期(默认)
|
||
week 按周时指定第几周(0 表示获取周次列表后取第一周)
|
||
|
||
返回同 get_timetable()。
|
||
"""
|
||
meta = self.get_semester_meta()
|
||
xnm = meta["xnm"]
|
||
xqm = meta["xqm"]
|
||
|
||
if meta.get("sfbczc") == "0":
|
||
raise RuntimeError("账号未完成缴费注册,无法查询课表(sfbczc=0)")
|
||
|
||
if kblx == "1":
|
||
weeks = self.get_week_list(xnm, xqm)
|
||
if not weeks:
|
||
raise RuntimeError("周次列表为空,无法按周查询")
|
||
idx = max(0, min(week, len(weeks) - 1))
|
||
zs = str(weeks[idx].get("zs", idx + 1))
|
||
return self.get_timetable(xnm, xqm, kblx="1", zs=zs)
|
||
else:
|
||
return self.get_timetable(xnm, xqm, kblx="2")
|
||
|
||
# ── 节次时间缓存 ──────────────────────────────────────────
|
||
|
||
def get_jc_times_cached(self, xnm: str, xqm: str, xqh_id: str) -> Dict[int, Dict]:
|
||
"""
|
||
获取节次时间并缓存为 {节次编号(int): {"qssj": "08:30", "jssj": "09:15"}} 的字典。
|
||
"""
|
||
if not hasattr(self, "_jc_cache"):
|
||
self._jc_cache: Dict[str, Dict[int, Dict]] = {}
|
||
cache_key = f"{xnm}_{xqm}_{xqh_id}"
|
||
if cache_key in self._jc_cache:
|
||
return self._jc_cache[cache_key]
|
||
|
||
raw = self.get_jc_times(xnm, xqm, xqh_id)
|
||
result: Dict[int, Dict] = {}
|
||
for item in raw:
|
||
try:
|
||
jc_no = int(item["jcmc"])
|
||
except (KeyError, ValueError):
|
||
continue
|
||
result[jc_no] = {
|
||
"qssj": item.get("qssj", "")[:5], # "08:30:00" -> "08:30"
|
||
"jssj": item.get("jssj", "")[:5],
|
||
"rsdmc": item.get("rsdmc", ""), # 上午/下午/晚上
|
||
}
|
||
self._jc_cache[cache_key] = result
|
||
return result
|
||
|
||
# ── 周次解析工具 ──────────────────────────────────────────
|
||
|
||
# 分段正则:匹配 "1-16周" / "3周" / "1-16" / "3" 等(周 字可省略)
|
||
_ZCD_SEG_RE = re.compile(r"(\d+)\s*(?:-\s*(\d+))?\s*周?")
|
||
|
||
@classmethod
|
||
def parse_zcd_weeks(cls, zcd: str) -> List[int]:
|
||
"""
|
||
解析周次描述字符串,返回确切的上课程周次列表(升序去重)。
|
||
|
||
与旧版 _zcd_contains_week 的关键区别:
|
||
单/双 标记只作用于**紧邻其前的那个分段**,而不是整条字符串。
|
||
例:"1-3周,5-7周(单),8-16周"
|
||
旧版(错):1-3 5-7 8-16 全部取奇 → [1,3,5,7,9,11,13,15](第2周误删)
|
||
新版(对):1-3 每周 + 5-7 取奇 + 8-16 每周
|
||
→ [1,2,3,5,7,8,9,10,11,12,13,14,15,16]
|
||
|
||
支持格式:
|
||
"1-16周" → 1..16
|
||
"1-15周(单)" → 1,3,...,15
|
||
"2周,8-16周(双)" → 2,8,10,12,14,16
|
||
"1-3周,5-7周(单),8-16周" → 1,2,3,5,7,8..16
|
||
"1周,5-7周(单)" → 1,5,7
|
||
"3" / "3-8"(无周字) → 同上
|
||
"""
|
||
if not zcd:
|
||
return []
|
||
|
||
# 兼容中文逗号/顿号/分号/空白分隔
|
||
text = zcd.replace(",", ",").replace("、", ",").replace(";", ",")
|
||
# 兼容全角括号与单双周的中英文写法
|
||
text = text.replace("(", "(").replace(")", ")")
|
||
text = text.replace("单周", "(单)").replace("双周", "(双)")
|
||
|
||
weeks: List[int] = []
|
||
seen = set()
|
||
|
||
# 按逗号拆段,逐段独立解析(每段可携带自己的 单/双 标记)
|
||
for seg in text.split(","):
|
||
seg = seg.strip()
|
||
if not seg:
|
||
continue
|
||
seg_odd = "(单)" in seg or seg.endswith("单")
|
||
seg_even = "(双)" in seg or seg.endswith("双")
|
||
# 去掉括号与单双字样后提取数字
|
||
seg_clean = re.sub(r"\([^)]*\)", "", seg)
|
||
seg_clean = seg_clean.replace("单", "").replace("双", "")
|
||
|
||
seg_weeks: List[int] = []
|
||
for m in cls._ZCD_SEG_RE.finditer(seg_clean):
|
||
start = int(m.group(1))
|
||
end = int(m.group(2)) if m.group(2) else start
|
||
if end < start:
|
||
start, end = end, start
|
||
seg_weeks.extend(range(start, end + 1))
|
||
|
||
if seg_odd:
|
||
seg_weeks = [w for w in seg_weeks if w % 2 == 1]
|
||
if seg_even:
|
||
seg_weeks = [w for w in seg_weeks if w % 2 == 0]
|
||
|
||
for w in seg_weeks:
|
||
if w not in seen:
|
||
seen.add(w)
|
||
weeks.append(w)
|
||
|
||
weeks.sort()
|
||
return weeks
|
||
|
||
@classmethod
|
||
def format_zcd_weeks(cls, weeks: List[int]) -> str:
|
||
"""
|
||
把周次列表格式化为通用周数描述(连续段用横杠,散周用逗号)。
|
||
|
||
例:[1,2,3,5,7,8,9,10,11,12,13,14,15,16] -> "1-3,5,7-16"
|
||
[2,8,10,12,14,16] -> "2,8,10,12,14,16"
|
||
[1..16] -> "1-16"
|
||
"""
|
||
if not weeks:
|
||
return ""
|
||
ws = sorted(set(weeks))
|
||
parts: List[str] = []
|
||
i = 0
|
||
n = len(ws)
|
||
while i < n:
|
||
j = i
|
||
while j + 1 < n and ws[j + 1] == ws[j] + 1:
|
||
j += 1
|
||
if j == i:
|
||
parts.append(str(ws[i]))
|
||
elif j == i + 1:
|
||
parts.append(f"{ws[i]},{ws[j]}") # 两周不成段,逗号更清晰
|
||
else:
|
||
parts.append(f"{ws[i]}-{ws[j]}")
|
||
i = j + 1
|
||
return ",".join(parts)
|
||
|
||
@classmethod
|
||
def _normalize_zcd_fields(cls, result: Any) -> Any:
|
||
"""
|
||
遍历课表接口返回,把每条课程的周次字段规范化为"通用周数":
|
||
|
||
zcd/qsjsz 重写为纯数字周数列表(如 "1,2,3,5,7,8,9,10,11,12,13,14,15,16"),
|
||
不再含 (单)/(双) 标记 —— 旧前端/app 沿用既有解析逻辑即可得到
|
||
正确周次,无需升级客户端
|
||
zcd_raw 教务系统原文(排查/展示用)
|
||
zcd_weeks 确切周次列表 [1,2,3,5,7,...]
|
||
zcd_desc 紧凑描述 "1-3,5,7-16"(连续段横杠、散周逗号)
|
||
|
||
解析失败(zcd 非空但 weeks 为空)时保留原文不动。
|
||
兼容 kbList / sjkList / jxhjkcList 三类列表,以及整个结果不是 dict 的情况。
|
||
"""
|
||
if not isinstance(result, dict):
|
||
return result
|
||
for key in ("kbList", "sjkList", "jxhjkcList"):
|
||
for course in result.get(key) or []:
|
||
if not isinstance(course, dict):
|
||
continue
|
||
raw = course.get("zcd") or course.get("qsjsz") or ""
|
||
if not raw:
|
||
continue
|
||
weeks = cls.parse_zcd_weeks(raw)
|
||
course["zcd_weeks"] = weeks
|
||
course["zcd_desc"] = cls.format_zcd_weeks(weeks)
|
||
course["zcd_raw"] = raw
|
||
if weeks:
|
||
generic = ",".join(str(w) for w in weeks)
|
||
if course.get("zcd"):
|
||
course["zcd"] = generic
|
||
if course.get("qsjsz"):
|
||
course["qsjsz"] = generic
|
||
return result
|
||
|
||
@staticmethod
|
||
def _zcd_contains_week(zcd: str, week: int) -> bool:
|
||
"""
|
||
判断周次描述字符串 zcd 是否包含指定周次。
|
||
|
||
实现已迁移到 parse_zcd_weeks(分段解析单双标记),此处仅做成员判断。
|
||
兼容两种输入:
|
||
- 教务系统原文 "1-3周,5-7周(单),8-16周"
|
||
- 规范化后的通用周数 "1,2,3,5,7,8,..."
|
||
空 zcd 或无法解析出任何周次时返回 True(视为无限制,宽容展示)。
|
||
支持格式举例:
|
||
"1-16周" → 1~16 每周
|
||
"1-15周(单)" → 1,3,5,...,15(奇数周)
|
||
"1-16周(双)" → 2,4,6,...,16(偶数周)
|
||
"1-11周,14-16周" → 1~11 及 14~16
|
||
"3周" → 仅第3周
|
||
"""
|
||
weeks = KbcxAPI.parse_zcd_weeks(zcd)
|
||
if not weeks:
|
||
return True
|
||
return week in weeks
|
||
|
||
# ── 课表空闲热度图 ─────────────────────────────────────
|
||
|
||
def get_heatmap_html(self) -> str:
|
||
"""
|
||
GET /kbcx/xskbcx_cxXskbBestSimpleIndex.html
|
||
|
||
返回课程空闲热度图的 HTML 表格字符串(颜色已修正)。
|
||
用绿色/橙色/红色标识各时间段空闲程度,用于已选课程弹窗展示。
|
||
"""
|
||
import time
|
||
import re
|
||
ts = int(time.time() * 1000)
|
||
url = f"{API_HEATMAP()}?_={ts}&gnmkdm=N253512"
|
||
r = self.session.get(url, timeout=15)
|
||
r.raise_for_status()
|
||
|
||
html = r.text
|
||
# 提取 <table...>...</table>
|
||
table_start = html.find('<table')
|
||
table_end = html.find('</table>', table_start)
|
||
if table_start == -1 or table_end == -1:
|
||
return html
|
||
table_html = html[table_start:table_end + 8]
|
||
|
||
# 提取 script 中的颜色修正逻辑并应用到表格
|
||
# script 中的模式:
|
||
# var stat = N;
|
||
# if(stat == 1){ $("#td_X-Y").css("background-color","#f0ad4e"); }
|
||
# else { $("#td_X-Y").css("background-color","#d9534f"); }
|
||
# stat=1 → 橙色, 否则 → 红色
|
||
script_start = html.find('<script')
|
||
script_end = html.find('</script>', script_start)
|
||
if script_start != -1 and script_end != -1:
|
||
script = html[script_start:script_end + 9]
|
||
# 逐块解析: var stat = N; ... #td_X-Y ... #f0ad4e ... #d9534f
|
||
for m in re.finditer(
|
||
r'var\s+stat\s*=\s*(\d+);.*?#td_(\d+-\d+).*?(#f0ad4e).*?(#d9534f)',
|
||
script, re.DOTALL
|
||
):
|
||
stat_val = int(m.group(1))
|
||
td_id = m.group(2)
|
||
new_color = '#f0ad4e' if stat_val == 1 else '#d9534f'
|
||
# 两步替换:先找到该 td 标签,再替换其中的 background-color
|
||
def _replace_color(tag_match):
|
||
tag = tag_match.group(0)
|
||
return re.sub(
|
||
r'(background-color:\s*)#[a-fA-F0-9]+',
|
||
rf'\1{new_color}',
|
||
tag
|
||
)
|
||
table_html = re.sub(
|
||
rf'<td[^>]*?id=["\']td_{re.escape(td_id)}["\'][^>]*?>',
|
||
_replace_color,
|
||
table_html
|
||
)
|
||
|
||
return table_html
|
||
|
||
# ── 格式化课表 ────────────────────────────────────────────
|
||
|
||
def format_timetable(
|
||
self,
|
||
kb_data: Dict,
|
||
week: Optional[int] = None,
|
||
xqh_id: str = "",
|
||
) -> Dict:
|
||
"""
|
||
将 get_timetable() 返回的原始数据格式化为结构化课表。
|
||
|
||
参数:
|
||
kb_data get_timetable() 的返回值
|
||
week 指定周次(int),None 表示不过滤(全学期所有课)
|
||
xqh_id 校区 ID,用于查节次时间;为空时自动从课表数据取
|
||
|
||
返回 dict:
|
||
week 本次过滤的周次(None 表示全学期)
|
||
xnm / xqm 学年学期
|
||
xsxx 学生信息
|
||
rqazcList 日期-星期对照(按周查询时有值)
|
||
jc_times {节次编号: {"qssj": "08:30", "jssj": "09:15", "rsdmc": "上午"}}
|
||
timetable {星期(1-7): [{课程信息...}]} 已含 jc_start/jc_end/time_range
|
||
sjk_list 实践课列表(同样过滤了周次)
|
||
"""
|
||
kb_list_raw = kb_data.get("kbList", [])
|
||
xsxx = kb_data.get("xsxx", {})
|
||
|
||
# xnm/xqm:顶层没有时从 kbList[0] 或 xsxx 取
|
||
xnm = (
|
||
kb_data.get("xnm")
|
||
or (kb_list_raw[0].get("xnm") if kb_list_raw else "")
|
||
or str(xsxx.get("XNM", ""))
|
||
)
|
||
xqm = (
|
||
kb_data.get("xqm")
|
||
or (kb_list_raw[0].get("xqm") if kb_list_raw else "")
|
||
or str(xsxx.get("XQM", ""))
|
||
)
|
||
|
||
# 优先取课表数据里的 xqh_id
|
||
if not xqh_id:
|
||
if kb_list_raw:
|
||
xqh_id = kb_list_raw[0].get("xqh_id", "")
|
||
|
||
# 节次时间
|
||
jc_times: Dict[int, Dict] = {}
|
||
if xqh_id and xnm and xqm:
|
||
try:
|
||
jc_times = self.get_jc_times_cached(xnm, xqm, xqh_id)
|
||
except Exception:
|
||
pass # 节次时间获取失败不影响课表结构
|
||
|
||
def _enrich(course: Dict) -> Dict:
|
||
"""给单条课程附加节次时间信息。"""
|
||
c = dict(course)
|
||
jcor = c.get("jcor", "") # e.g. "3-4"
|
||
try:
|
||
parts = [int(x) for x in jcor.split("-") if x.strip()]
|
||
jc_start = parts[0] if parts else 0
|
||
jc_end = parts[-1] if len(parts) > 1 else jc_start
|
||
except ValueError:
|
||
jc_start = jc_end = 0
|
||
|
||
c["jc_start"] = jc_start
|
||
c["jc_end"] = jc_end
|
||
|
||
if jc_start and jc_times:
|
||
t_start = jc_times.get(jc_start, {}).get("qssj", "")
|
||
t_end = jc_times.get(jc_end, {}).get("jssj", "")
|
||
rsdmc = jc_times.get(jc_start, {}).get("rsdmc", "")
|
||
c["time_start"] = t_start
|
||
c["time_end"] = t_end
|
||
c["time_range"] = f"{t_start}~{t_end}" if t_start and t_end else ""
|
||
c["rsdmc"] = rsdmc
|
||
else:
|
||
c["time_start"] = c["time_end"] = c["time_range"] = c["rsdmc"] = ""
|
||
|
||
return c
|
||
|
||
def _week_ok(course: Dict) -> bool:
|
||
if week is None:
|
||
return True
|
||
return self._zcd_contains_week(course.get("zcd", ""), week)
|
||
|
||
# 组装 timetable: {xqj(int): [course, ...]}
|
||
timetable: Dict[int, List[Dict]] = {d: [] for d in range(1, 8)}
|
||
for raw_c in kb_data.get("kbList", []):
|
||
if not _week_ok(raw_c):
|
||
continue
|
||
c = _enrich(raw_c)
|
||
day = int(c.get("xqj", 0))
|
||
if 1 <= day <= 7:
|
||
timetable[day].append(c)
|
||
|
||
# 按节次排序
|
||
for day in timetable:
|
||
timetable[day].sort(key=lambda x: x.get("jc_start", 0))
|
||
|
||
# 实践课
|
||
sjk_list = [
|
||
_enrich(c) for c in kb_data.get("sjkList", [])
|
||
if _week_ok(c)
|
||
]
|
||
|
||
return {
|
||
"week": week,
|
||
"xnm": xnm,
|
||
"xqm": xqm,
|
||
"xsxx": kb_data.get("xsxx", {}),
|
||
"rqazcList": kb_data.get("rqazcList", []),
|
||
"jc_times": jc_times,
|
||
"timetable": timetable,
|
||
"sjk_list": sjk_list,
|
||
}
|
||
|
||
# ── 打印课表 ──────────────────────────────────────────────
|
||
|
||
@staticmethod
|
||
def print_timetable(fmt: Dict, show_location: bool = True) -> None:
|
||
"""
|
||
将 format_timetable() 的结果打印到终端。
|
||
|
||
参数:
|
||
fmt format_timetable() 返回值
|
||
show_location 是否显示教室位置(默认 True)
|
||
"""
|
||
DAY_NAMES = ["", "周一", "周二", "周三", "周四", "周五", "周六", "周日"]
|
||
xsxx = fmt.get("xsxx", {})
|
||
week = fmt.get("week")
|
||
xnm = fmt.get("xnm", "")
|
||
xqm = fmt.get("xqm", "")
|
||
xqm_cn = "第一学期" if xqm == "3" else "第二学期"
|
||
|
||
# 头部信息
|
||
name = xsxx.get("XM", "")
|
||
bjmc = xsxx.get("BJMC", "")
|
||
week_label = f"第{week}周 " if week is not None else "(全学期)"
|
||
print(f"\n{'='*60}")
|
||
print(f" {name} {bjmc} {xnm}-{int(xnm)+1}学年 {xqm_cn} {week_label}")
|
||
print(f"{'='*60}")
|
||
|
||
# 日期行(按周查询时有 rqazcList)
|
||
rq_map: Dict[int, str] = {}
|
||
for item in fmt.get("rqazcList", []):
|
||
rq_map[int(item["xqj"])] = item.get("rq", "")
|
||
|
||
timetable = fmt["timetable"]
|
||
# 只打印有课的天 + 星期一~五(至少保留)
|
||
active_days = sorted(
|
||
set(d for d in range(1, 8) if timetable[d]) | set(range(1, 6))
|
||
)
|
||
|
||
for day in active_days:
|
||
courses = timetable[day]
|
||
day_name = DAY_NAMES[day]
|
||
date_str = f" ({rq_map[day]})" if day in rq_map else ""
|
||
print(f"\n 【{day_name}{date_str}】")
|
||
if not courses:
|
||
print(" (无课)")
|
||
continue
|
||
for c in courses:
|
||
kcmc = c.get("kcmc", "")
|
||
xm = c.get("xm", "")
|
||
jcor = c.get("jcor", "")
|
||
zcd = c.get("zcd", "")
|
||
time_r = c.get("time_range", "")
|
||
rsdmc = c.get("rsdmc", "")
|
||
cdmc = c.get("cdmc", "")
|
||
xsdm = c.get("xsdm", "01") # 01=理论 02=实践
|
||
type_tag = "△" if xsdm == "02" else "☆"
|
||
|
||
# 第几节
|
||
jc_start = c.get("jc_start", 0)
|
||
jc_end = c.get("jc_end", 0)
|
||
jc_label = f"第{jc_start}-{jc_end}节" if jc_start else ""
|
||
|
||
time_label = f"{time_r} ({rsdmc})" if time_r else jc_label
|
||
|
||
loc_part = f" @ {cdmc}" if show_location and cdmc else ""
|
||
print(f" {type_tag} [{time_label}] {kcmc} /{xm} [{zcd}]{loc_part}")
|
||
|
||
# 实践课(如有)
|
||
sjk = fmt.get("sjk_list", [])
|
||
if sjk:
|
||
print(f"\n 【实践课】")
|
||
for c in sjk:
|
||
print(f" △ {c.get('kcmc','')} /{c.get('xm','')} [{c.get('qsjsz','')}]")
|
||
|
||
# 节次时间表(可选,附在末尾)
|
||
jc_times = fmt.get("jc_times", {})
|
||
if jc_times:
|
||
print(f"\n 【节次时间】")
|
||
last_rsd = ""
|
||
for jc_no in sorted(jc_times):
|
||
info = jc_times[jc_no]
|
||
rsd = info.get("rsdmc", "")
|
||
if rsd != last_rsd:
|
||
print(f" {rsd}")
|
||
last_rsd = rsd
|
||
print(f" 第{jc_no}节 {info['qssj']}~{info['jssj']}")
|
||
|
||
print(f"\n{'='*60}\n")
|
||
|
||
|
||
# ── CLI 快速测试 ──────────────────────────────────────────────
|
||
if __name__ == "__main__":
|
||
import sys
|
||
|
||
username = sys.argv[1] if len(sys.argv) > 1 else "253051601132"
|
||
# 可选:指定周次,例如 python kbcx_api.py 253051601132 3
|
||
week_arg: Optional[int] = int(sys.argv[2]) if len(sys.argv) > 2 else None
|
||
|
||
print(f"[kbcx_api] 测试账号: {username}")
|
||
|
||
api = KbcxAPI(username)
|
||
|
||
# 1. 学期参数
|
||
print("\n--- get_semester_meta ---")
|
||
meta = api.get_semester_meta()
|
||
print(json.dumps(meta, ensure_ascii=False, indent=2))
|
||
|
||
# 2. 周次列表
|
||
print("\n--- get_week_list ---")
|
||
weeks = api.get_week_list(meta["xnm"], meta["xqm"])
|
||
print(f"共 {len(weeks)} 周")
|
||
if weeks:
|
||
# 自动推断当前周(如未指定则取第一周)
|
||
if week_arg is None:
|
||
week_arg = int(weeks[0].get("zs", 1))
|
||
print(f"使用第 {week_arg} 周进行展示")
|
||
|
||
# 3. 查全学期课表(用于按周过滤)
|
||
print("\n--- get_timetable (kblx=2, 全学期) ---")
|
||
kb = api.get_timetable(meta["xnm"], meta["xqm"], kblx="2")
|
||
courses_raw = kb.get("kbList", [])
|
||
print(f"原始课程条数: {len(courses_raw)}")
|
||
|
||
# 4. xqh_id
|
||
xqh_id = meta.get("xqh_id") or (courses_raw[0].get("xqh_id") if courses_raw else "")
|
||
|
||
# 5. 节次时间
|
||
if xqh_id:
|
||
print(f"\n--- get_jc_times (xqh_id={xqh_id}) ---")
|
||
jc = api.get_jc_times_cached(meta["xnm"], meta["xqm"], xqh_id)
|
||
for no in sorted(jc):
|
||
info = jc[no]
|
||
print(f" 第{no}节 {info['qssj']}~{info['jssj']} ({info['rsdmc']})")
|
||
else:
|
||
print("\n[跳过] xqh_id 为空")
|
||
|
||
# 6. 格式化并打印课表
|
||
print("\n--- format_timetable & print ---")
|
||
fmt = api.format_timetable(kb, week=week_arg, xqh_id=xqh_id)
|
||
api.print_timetable(fmt)
|
||
|