421 lines
15 KiB
Python
421 lines
15 KiB
Python
#!/usr/bin/env python3
|
||
"""Extract all selectable classes from Najah without launching a browser."""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import csv
|
||
import getpass
|
||
import json
|
||
import os
|
||
import re
|
||
import sys
|
||
import time
|
||
from dataclasses import asdict, dataclass
|
||
from datetime import datetime, timezone
|
||
from pathlib import Path
|
||
from typing import Any, Iterable
|
||
from urllib.parse import urljoin, urlparse
|
||
|
||
import requests
|
||
from bs4 import BeautifulSoup, Tag
|
||
|
||
|
||
LOGIN_PAGE_URL = "http://login.ismc.ir/?refurl=http:%2F%2Fnajah.ismc.ir"
|
||
AUTH_URL = "http://login.ismc.ir/api/Auth/Authentication"
|
||
NAJAH_URL = "http://najah.ismc.ir/"
|
||
REGISTER_URL = "http://najah.ismc.ir/Students/ClassRegister.aspx"
|
||
GRID_ID = "ContentPlaceHolder1_CtlSelectionUnits1_SelectableUnitsGridView"
|
||
PERIOD_ID = "ContentPlaceHolder1_CTLGroupPeriod1_DDLPeriod"
|
||
NEXT_ID = "BtnGotoStep2"
|
||
|
||
PERSIAN_DIGITS = str.maketrans("۰۱۲۳۴۵۶۷۸۹٠١٢٣٤٥٦٧٨٩", "01234567890123456789")
|
||
POSTBACK_RE = re.compile(
|
||
r"WebForm_PostBackOptions\(\s*['\"]([^'\"]+)['\"]\s*,\s*['\"]([^'\"]*)",
|
||
re.IGNORECASE,
|
||
)
|
||
|
||
|
||
class ScrapeError(RuntimeError):
|
||
pass
|
||
|
||
|
||
@dataclass(slots=True)
|
||
class ClassRow:
|
||
academic_year: str
|
||
group: str
|
||
lesson_group: str
|
||
row_number: str
|
||
availability: str
|
||
lesson: str
|
||
class_title: str
|
||
semester: str | None
|
||
hours: str
|
||
teacher: str
|
||
scope: str
|
||
location: str
|
||
remaining_capacity: str
|
||
days: list[str]
|
||
time: str | None
|
||
schedule_raw: str
|
||
|
||
|
||
def clean_text(value: Any) -> str:
|
||
return re.sub(r"\s+", " ", str(value or "")).strip()
|
||
|
||
|
||
def to_english_digits(value: str) -> str:
|
||
return value.translate(PERSIAN_DIGITS)
|
||
|
||
|
||
def parse_semester(class_title: str) -> str | None:
|
||
if re.search(r"نیمسال\s*اول", class_title):
|
||
return "نیمسال اول"
|
||
if re.search(r"نیمسال\s*دوم", class_title):
|
||
return "نیمسال دوم"
|
||
return None
|
||
|
||
|
||
def parse_schedule(value: str) -> tuple[list[str], str | None, str | None]:
|
||
normalized = clean_text(value)
|
||
match = re.match(r"^(.*):([^:]+):\[([^\]]+)]$", normalized)
|
||
if not match:
|
||
return [], None, None
|
||
location, days_text, time = map(clean_text, match.groups())
|
||
days = [clean_text(day) for day in re.split(r"[،,]", days_text) if clean_text(day)]
|
||
return days, time or None, location or None
|
||
|
||
|
||
def response_data(payload: dict[str, Any]) -> dict[str, Any]:
|
||
data = payload.get("data", payload)
|
||
if not isinstance(data, dict):
|
||
raise ScrapeError("پاسخ API ورود ساختار شناختهشدهای ندارد.")
|
||
return data
|
||
|
||
|
||
def authenticate(
|
||
session: requests.Session,
|
||
username: str,
|
||
password: str,
|
||
timeout: float,
|
||
) -> None:
|
||
session.get(LOGIN_PAGE_URL, timeout=timeout).raise_for_status()
|
||
response = session.post(
|
||
AUTH_URL,
|
||
json={
|
||
"userName": to_english_digits(username),
|
||
"password": to_english_digits(password),
|
||
"stayOn": 1,
|
||
"url": NAJAH_URL.rstrip("/"),
|
||
},
|
||
timeout=timeout,
|
||
)
|
||
response.raise_for_status()
|
||
try:
|
||
data = response_data(response.json())
|
||
except requests.exceptions.JSONDecodeError as error:
|
||
raise ScrapeError("API ورود پاسخ JSON معتبر برنگرداند.") from error
|
||
|
||
result = int(data.get("Result") or 0)
|
||
token = data.get("Token")
|
||
if result <= 0 or not token:
|
||
message = token if isinstance(token, str) and token else "نام کاربری یا رمز عبور نادرست است."
|
||
raise ScrapeError(message)
|
||
if int(data.get("Mode") or 0) == 1:
|
||
raise ScrapeError("این حساب احراز هویت دومرحلهای دارد؛ پشتیبانی آن هنوز اضافه نشده است.")
|
||
if data.get("IsPerLoginRequierment") is True:
|
||
raise ScrapeError("سامانه تکمیل اطلاعات پروفایل را پیش از ورود الزامی کرده است.")
|
||
|
||
landing = session.get(NAJAH_URL, params={"token": token}, timeout=timeout)
|
||
landing.raise_for_status()
|
||
if urlparse(landing.url).hostname != "najah.ismc.ir":
|
||
raise ScrapeError("توکن پذیرفته شد، اما نشست نجاح ساخته نشد.")
|
||
|
||
|
||
def successful_form_fields(soup: BeautifulSoup) -> dict[str, str]:
|
||
form = soup.find("form")
|
||
if not isinstance(form, Tag):
|
||
raise ScrapeError("فرم ASP.NET در صفحه پیدا نشد.")
|
||
|
||
fields: dict[str, str] = {}
|
||
for control in form.find_all(["input", "select", "textarea"]):
|
||
name = control.get("name")
|
||
if not name or control.has_attr("disabled"):
|
||
continue
|
||
if control.name == "input":
|
||
kind = (control.get("type") or "text").lower()
|
||
if kind in {"submit", "button", "image", "file", "reset"}:
|
||
continue
|
||
if kind in {"checkbox", "radio"} and not control.has_attr("checked"):
|
||
continue
|
||
fields[name] = control.get("value", "")
|
||
elif control.name == "select":
|
||
selected = control.find("option", selected=True) or control.find("option")
|
||
fields[name] = selected.get("value", "") if isinstance(selected, Tag) else ""
|
||
else:
|
||
fields[name] = control.get_text()
|
||
return fields
|
||
|
||
|
||
def form_action(current_url: str, soup: BeautifulSoup) -> str:
|
||
form = soup.find("form")
|
||
action = form.get("action", "") if isinstance(form, Tag) else ""
|
||
return urljoin(current_url, action)
|
||
|
||
|
||
def post_form(
|
||
session: requests.Session,
|
||
response: requests.Response,
|
||
soup: BeautifulSoup,
|
||
extra: dict[str, str],
|
||
timeout: float,
|
||
) -> tuple[requests.Response, BeautifulSoup]:
|
||
fields = successful_form_fields(soup)
|
||
fields.update(extra)
|
||
result = session.post(
|
||
form_action(response.url, soup),
|
||
data=fields,
|
||
timeout=timeout,
|
||
)
|
||
result.raise_for_status()
|
||
return result, BeautifulSoup(result.content, "html.parser")
|
||
|
||
|
||
def postback_target(anchor: Tag) -> tuple[str, str] | None:
|
||
match = POSTBACK_RE.search(anchor.get("href", ""))
|
||
return match.groups() if match else None
|
||
|
||
|
||
def lesson_groups(soup: BeautifulSoup) -> list[tuple[str, str, str]]:
|
||
excluded = {"درس", "واحد/ساعت", "محدوده", "مکان", "ظرفیت مانده"}
|
||
found: list[tuple[str, str, str]] = []
|
||
seen: set[str] = set()
|
||
grid = soup.find("table", id=GRID_ID)
|
||
|
||
for anchor in soup.find_all("a", href=True):
|
||
target = postback_target(anchor)
|
||
if not target:
|
||
continue
|
||
if grid and anchor.find_parent("table", id=GRID_ID):
|
||
continue
|
||
title = re.sub(r"^[^\w\u0600-\u06ff]+", "", clean_text(anchor.get_text(" ")))
|
||
if not title or title in excluded or title in seen:
|
||
continue
|
||
seen.add(title)
|
||
found.append((title, target[0], target[1]))
|
||
return found
|
||
|
||
|
||
def select_academic_year(
|
||
session: requests.Session,
|
||
response: requests.Response,
|
||
soup: BeautifulSoup,
|
||
year: str | None,
|
||
timeout: float,
|
||
) -> tuple[requests.Response, BeautifulSoup, str]:
|
||
select = soup.find("select", id=PERIOD_ID)
|
||
if not isinstance(select, Tag):
|
||
return response, soup, ""
|
||
|
||
options = select.find_all("option")
|
||
chosen = next((o for o in options if o.has_attr("selected")), options[0] if options else None)
|
||
if year:
|
||
chosen = next((o for o in options if year in clean_text(o.get_text())), None)
|
||
if not isinstance(chosen, Tag):
|
||
raise ScrapeError(f"سال تحصیلی «{year}» در سامانه پیدا نشد.")
|
||
name = select.get("name")
|
||
if not name:
|
||
raise ScrapeError("نام کنترل سال تحصیلی پیدا نشد.")
|
||
response, soup = post_form(
|
||
session,
|
||
response,
|
||
soup,
|
||
{"__EVENTTARGET": name, "__EVENTARGUMENT": "", name: chosen.get("value", "")},
|
||
timeout,
|
||
)
|
||
select = soup.find("select", id=PERIOD_ID)
|
||
if isinstance(select, Tag):
|
||
chosen = select.find("option", selected=True) or select.find("option")
|
||
return response, soup, clean_text(chosen.get_text()) if isinstance(chosen, Tag) else ""
|
||
|
||
|
||
def enter_selection_step(
|
||
session: requests.Session,
|
||
timeout: float,
|
||
) -> tuple[requests.Response, BeautifulSoup]:
|
||
response = session.get(REGISTER_URL, timeout=timeout)
|
||
response.raise_for_status()
|
||
if urlparse(response.url).hostname == "login.ismc.ir":
|
||
raise ScrapeError("نشست ورود پیش از رسیدن به انتخاب درس از بین رفت.")
|
||
soup = BeautifulSoup(response.content, "html.parser")
|
||
if soup.find("table", id=GRID_ID):
|
||
return response, soup
|
||
|
||
button = soup.find(id=NEXT_ID)
|
||
if not isinstance(button, Tag) or not button.get("name"):
|
||
raise ScrapeError("دکمه مرحله بعد صفحه انتخاب درس پیدا نشد.")
|
||
return post_form(
|
||
session,
|
||
response,
|
||
soup,
|
||
{button["name"]: button.get("value", "مرحله بعدی")},
|
||
timeout,
|
||
)
|
||
|
||
|
||
def extract_rows(soup: BeautifulSoup, year: str, group: str, lesson_group: str) -> list[ClassRow]:
|
||
table = soup.find("table", id=GRID_ID)
|
||
if not isinstance(table, Tag):
|
||
raise ScrapeError("جدول کلاسهای قابل انتخاب پیدا نشد.")
|
||
|
||
records: list[ClassRow] = []
|
||
for row in table.find_all("tr")[1:]:
|
||
cells = row.find_all("td", recursive=False)
|
||
if len(cells) < 10:
|
||
continue
|
||
values = [clean_text(cell.get_text(" ")) for cell in cells]
|
||
time_control = cells[9].find(["input", "textarea"])
|
||
schedule_raw = clean_text(
|
||
time_control.get("value", "") if isinstance(time_control, Tag) else values[9]
|
||
)
|
||
days, time, schedule_location = parse_schedule(schedule_raw)
|
||
records.append(
|
||
ClassRow(
|
||
academic_year=year,
|
||
group=group,
|
||
lesson_group=lesson_group,
|
||
row_number=values[0],
|
||
availability="قابل انتخاب" if cells[1].find("select") else values[1],
|
||
lesson=values[2],
|
||
class_title=values[3],
|
||
semester=parse_semester(values[3]),
|
||
hours=values[4],
|
||
teacher=values[5],
|
||
scope=values[6],
|
||
location=values[7] or schedule_location or "",
|
||
remaining_capacity=values[8],
|
||
days=days,
|
||
time=time,
|
||
schedule_raw=schedule_raw,
|
||
)
|
||
)
|
||
return records
|
||
|
||
|
||
def scrape(
|
||
username: str,
|
||
password: str,
|
||
year: str | None,
|
||
timeout: float,
|
||
delay: float,
|
||
) -> dict[str, Any]:
|
||
session = requests.Session()
|
||
session.headers.update(
|
||
{
|
||
"User-Agent": "ClassRegister/0.2 (+requests; personal educational helper)",
|
||
"Accept-Language": "fa-IR,fa;q=0.9,en;q=0.5",
|
||
}
|
||
)
|
||
authenticate(session, username, password, timeout)
|
||
response, soup = enter_selection_step(session, timeout)
|
||
response, soup, academic_year = select_academic_year(
|
||
session, response, soup, year, timeout
|
||
)
|
||
group_element = soup.find(id="SelectGroupButton")
|
||
group = clean_text(group_element.get_text(" ")) if isinstance(group_element, Tag) else ""
|
||
groups = lesson_groups(soup)
|
||
if not groups:
|
||
raise ScrapeError("هیچ عنوان درسی در پنل انتخاب درس پیدا نشد.")
|
||
|
||
classes: list[ClassRow] = []
|
||
errors: list[dict[str, str]] = []
|
||
print(f"{len(groups)} دسته درس پیدا شد.")
|
||
for index, (title, target, argument) in enumerate(groups, start=1):
|
||
print(f"[{index}/{len(groups)}] {title} ... ", end="", flush=True)
|
||
try:
|
||
response, soup = post_form(
|
||
session,
|
||
response,
|
||
soup,
|
||
{"__EVENTTARGET": target, "__EVENTARGUMENT": argument},
|
||
timeout,
|
||
)
|
||
rows = extract_rows(soup, academic_year, group, title)
|
||
classes.extend(rows)
|
||
print(f"{len(rows)} کلاس")
|
||
except Exception as error: # continue other lesson groups and report partial failures
|
||
errors.append({"lesson_group": title, "message": str(error)})
|
||
print(f"خطا: {error}")
|
||
if delay > 0 and index < len(groups):
|
||
time.sleep(delay)
|
||
|
||
return {
|
||
"exported_at": datetime.now(timezone.utc).isoformat(),
|
||
"source": REGISTER_URL,
|
||
"academic_year": academic_year,
|
||
"group": group,
|
||
"lesson_group_count": len(groups),
|
||
"class_count": len(classes),
|
||
"errors": errors,
|
||
"classes": [asdict(item) for item in classes],
|
||
}
|
||
|
||
|
||
def write_outputs(result: dict[str, Any], output_dir: Path) -> tuple[Path, Path]:
|
||
output_dir.mkdir(parents=True, exist_ok=True)
|
||
safe_year = re.sub(r"[^0-9۰-۹_-]+", "-", result["academic_year"] or "current")
|
||
json_path = output_dir / f"classes-{safe_year}.json"
|
||
csv_path = output_dir / f"classes-{safe_year}.csv"
|
||
json_path.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||
|
||
columns = [field.name for field in ClassRow.__dataclass_fields__.values()]
|
||
with csv_path.open("w", encoding="utf-8-sig", newline="") as stream:
|
||
writer = csv.DictWriter(stream, fieldnames=columns)
|
||
writer.writeheader()
|
||
for item in result["classes"]:
|
||
row = dict(item)
|
||
row["days"] = "، ".join(row["days"])
|
||
writer.writerow(row)
|
||
return json_path, csv_path
|
||
|
||
|
||
def credentials() -> tuple[str, str]:
|
||
username = os.getenv("ISMC_USERNAME") or input("نام کاربری: ").strip()
|
||
password = os.getenv("ISMC_PASSWORD") or getpass.getpass("رمز عبور: ")
|
||
if not username or not password:
|
||
raise ScrapeError("نام کاربری و رمز عبور الزامیاند.")
|
||
return username, password
|
||
|
||
|
||
def parse_args(argv: Iterable[str] | None = None) -> argparse.Namespace:
|
||
parser = argparse.ArgumentParser(description="استخراج کلاسهای نجاح بدون مرورگر")
|
||
parser.add_argument("--year", help="سال تحصیلی، مانند 1406-1405")
|
||
parser.add_argument("--output", type=Path, default=Path("output"), help="پوشه خروجی")
|
||
parser.add_argument("--timeout", type=float, default=30, help="مهلت هر درخواست، بر حسب ثانیه")
|
||
parser.add_argument(
|
||
"--delay",
|
||
type=float,
|
||
default=0.25,
|
||
help="مکث بین درخواست گروههای درسی، بر حسب ثانیه",
|
||
)
|
||
return parser.parse_args(argv)
|
||
|
||
|
||
def main() -> int:
|
||
args = parse_args()
|
||
try:
|
||
username, password = credentials()
|
||
result = scrape(username, password, args.year, args.timeout, max(0, args.delay))
|
||
json_path, csv_path = write_outputs(result, args.output.resolve())
|
||
print(f"\n{result['class_count']} کلاس استخراج شد.")
|
||
print(f"JSON: {json_path}")
|
||
print(f"CSV: {csv_path}")
|
||
return 2 if result["errors"] else 0
|
||
except (ScrapeError, requests.RequestException) as error:
|
||
print(f"خطا: {error}", file=sys.stderr)
|
||
return 1
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main())
|