| |
| """Re-fetch BBRef player pages for draft rows missing high_school_finish. |
| |
| Fixes the High School vs High Schools: parser gap without full --force re-scrape. |
| |
| Usage: |
| python repair_missing_hs.py |
| python repair_missing_hs.py --years 2020-2025 |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import csv |
| import time |
| from pathlib import Path |
|
|
| import requests |
|
|
| from fetch_bbref_draft_hs import ( |
| SLEEP_S, |
| UA, |
| load_cache, |
| parse_player_hs, |
| parse_years, |
| save_cache, |
| ) |
|
|
| ROOT = Path(__file__).resolve().parents[1] |
| RAW = ROOT / "sources" / "bbref_raw" |
|
|
|
|
| def repair_year(session: requests.Session, year: int, cache: dict) -> int: |
| path = RAW / f"draft_{year}.csv" |
| if not path.exists(): |
| print(f"[{year}] missing {path}") |
| return 0 |
| with path.open(encoding="utf-8") as f: |
| rows = list(csv.DictReader(f)) |
| fields = list(rows[0].keys()) if rows else [] |
| fixed = 0 |
| for i, row in enumerate(rows, 1): |
| if (row.get("high_school_finish") or "").strip(): |
| continue |
| url = (row.get("bbref_player_url") or "").strip() |
| slug = (row.get("bbref_player_slug") or "").strip() |
| if not url or not slug: |
| continue |
| print(f" [{year} {i}/{len(rows)}] refetch {row['player_name']} ({slug})") |
| time.sleep(SLEEP_S) |
| try: |
| r = session.get(url, timeout=45) |
| r.raise_for_status() |
| r.encoding = "utf-8" |
| hs = parse_player_hs(r.text) |
| hs["fetched"] = True |
| hs["repaired"] = True |
| except requests.HTTPError as e: |
| print(f" HTTP error: {e}") |
| continue |
| cache[slug] = hs |
| if hs.get("high_school_finish"): |
| row["high_school_finish"] = hs["high_school_finish"] |
| row["hs_city"] = hs.get("hs_city", "") |
| row["hs_state"] = hs.get("hs_state", "") |
| row["hs_raw"] = hs.get("hs_raw", "") |
| row["birth_place"] = hs.get("birth_place", "") or row.get("birth_place", "") |
| row["hs_source"] = "basketball_reference_player_page_repaired" |
| fixed += 1 |
| print(f" -> {hs['high_school_finish']} ({hs.get('hs_city')}, {hs.get('hs_state')})") |
| if i % 5 == 0: |
| save_cache(cache) |
| with path.open("w", newline="", encoding="utf-8") as f: |
| w = csv.DictWriter(f, fieldnames=fields, extrasaction="ignore") |
| w.writeheader() |
| w.writerows(rows) |
| print(f"[{year}] fixed {fixed} previously missing HS rows") |
| return fixed |
|
|
|
|
| def main() -> None: |
| ap = argparse.ArgumentParser() |
| ap.add_argument("--years", default="2016-2025") |
| args = ap.parse_args() |
| years = parse_years(args.years) |
| cache = load_cache() |
| session = requests.Session() |
| session.headers.update({"User-Agent": UA, "Accept-Language": "en-US,en;q=0.9"}) |
| total = 0 |
| for year in years: |
| total += repair_year(session, year, cache) |
| save_cache(cache) |
| print(f"done; fixed {total} rows") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|