File size: 9,580 Bytes
e94c8f8 | 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 | #!/usr/bin/env python3
"""Fetch NBA draft picks + finishing high school from Basketball-Reference.
Polite scraper: ~1 request / 3.5s. Caches player pages so re-runs are cheap.
Usage:
python fetch_bbref_draft_hs.py --years 2016-2025
python fetch_bbref_draft_hs.py --years 2022,2023,2024
"""
from __future__ import annotations
import argparse
import csv
import json
import re
import time
from pathlib import Path
import requests
from bs4 import BeautifulSoup
ROOT = Path(__file__).resolve().parents[1]
RAW = ROOT / "sources" / "bbref_raw"
CACHE = RAW / "player_hs_cache.json"
UA = (
"athletic_scrapper-nba-draft-hs-panel/0.1 "
"(research dataset; polite scrape; github.com/Dharit13)"
)
SLEEP_S = 3.5
BASE = "https://www.basketball-reference.com"
def parse_years(spec: str) -> list[int]:
years: list[int] = []
for part in spec.split(","):
part = part.strip()
if not part:
continue
if "-" in part:
a, b = part.split("-", 1)
years.extend(range(int(a), int(b) + 1))
else:
years.append(int(part))
return sorted(set(years))
def load_cache() -> dict:
if CACHE.exists():
return json.loads(CACHE.read_text())
return {}
def save_cache(cache: dict) -> None:
RAW.mkdir(parents=True, exist_ok=True)
CACHE.write_text(json.dumps(cache, indent=2, sort_keys=True) + "\n")
def get_html(session: requests.Session, url: str) -> str:
r = session.get(url, timeout=45)
r.raise_for_status()
# Basketball-Reference is UTF-8; avoid mojibake from mis-detected encoding.
r.encoding = "utf-8"
return r.text
def parse_draft_table(html: str, year: int) -> list[dict]:
soup = BeautifulSoup(html, "html.parser")
table = soup.find("table", id="stats")
if table is None:
raise RuntimeError(f"No #stats table for {year}")
rows_out: list[dict] = []
for tr in table.find("tbody").find_all("tr"):
if tr.get("class") and "thead" in tr.get("class"):
continue
pick_cell = tr.find("td", {"data-stat": "pick_overall"})
if pick_cell is None:
continue
pick_txt = pick_cell.get_text(strip=True)
if not pick_txt.isdigit():
continue
pick = int(pick_txt)
team_cell = tr.find("td", {"data-stat": "team_id"})
player_cell = tr.find("td", {"data-stat": "player"})
college_cell = tr.find("td", {"data-stat": "college_name"})
a = player_cell.find("a") if player_cell else None
player_name = player_cell.get_text(strip=True) if player_cell else ""
player_url = BASE + a["href"] if a and a.get("href") else ""
player_slug = a["href"].rstrip("/").split("/")[-1].replace(".html", "") if a else ""
team = team_cell.get_text(strip=True) if team_cell else ""
college = college_cell.get_text(strip=True) if college_cell else ""
rnd = 1 if pick <= 30 else 2
rows_out.append(
{
"draft_year": year,
"pick": pick,
"round": rnd,
"player_name": player_name,
"nba_team": team,
"college_or_prior": college,
"bbref_player_url": player_url,
"bbref_player_slug": player_slug,
}
)
return rows_out
def _parse_one_hs_entry(entry: str) -> tuple[str, str, str]:
"""Parse 'School in City, State' → (school, city, state)."""
entry = entry.strip(" ,")
if not entry:
return "", "", ""
if " in " in entry:
school, loc = entry.rsplit(" in ", 1)
school = school.strip()
loc = loc.strip()
if "," in loc:
city, state = loc.rsplit(",", 1)
return school, city.strip(), state.strip()
return school, loc, ""
return entry, "", ""
_HS_ENTRY_RE = re.compile(
r"(.+?)\s+in\s+(.+?)(?=,\s*[^,]+?\s+in\s+|$)",
re.IGNORECASE,
)
def split_hs_entries(body: str) -> list[str]:
"""Split BBRef multi-school bio lines into individual 'School in City, Region' entries."""
body = body.strip()
if not body:
return []
matches = list(_HS_ENTRY_RE.finditer(body))
if not matches:
return [body]
return [
f"{m.group(1).strip().lstrip(',').strip()} in {m.group(2).strip()}"
for m in matches
]
def apply_hs_body(out: dict, body: str) -> None:
parts = split_hs_entries(body)
out["hs_all"] = " | ".join(parts)
school, city, state = _parse_one_hs_entry(parts[-1])
out["high_school_finish"] = school
out["hs_city"] = city
out["hs_state"] = state
def parse_player_hs(html: str) -> dict:
"""Return high_school_finish, hs_city, hs_state, birth_country_hint.
Basketball-Reference uses:
- 'High School: X in City, State' for a single school
- 'High Schools: A in ..., B in ...' for multiple — we take the **last**
entry as the finishing school (same convention as the 2026 case study).
"""
soup = BeautifulSoup(html, "html.parser")
out = {
"high_school_finish": "",
"hs_city": "",
"hs_state": "",
"hs_raw": "",
"birth_place": "",
"hs_all": "",
}
meta = soup.find("div", id="meta")
if meta is None:
return out
for p in meta.find_all("p"):
text = " ".join(p.get_text(" ", strip=True).split())
if text.startswith("Born:"):
out["birth_place"] = text.replace("Born:", "").strip()
if text.startswith("High School:") or text.startswith("High Schools:"):
out["hs_raw"] = text
if text.startswith("High Schools:"):
body = text[len("High Schools:") :].strip()
else:
body = text[len("High School:") :].strip()
apply_hs_body(out, body)
return out
def parse_hs_raw_line(hs_raw: str) -> dict:
"""Re-parse a cached hs_raw line without network I/O."""
out = {
"high_school_finish": "",
"hs_city": "",
"hs_state": "",
"hs_raw": hs_raw or "",
"hs_all": "",
}
if not hs_raw:
return out
text = hs_raw.strip()
if text.startswith("High Schools:"):
body = text[len("High Schools:") :].strip()
elif text.startswith("High School:"):
body = text[len("High School:") :].strip()
else:
body = text
apply_hs_body(out, body)
return out
def fetch_year(session: requests.Session, year: int, cache: dict, force: bool) -> list[dict]:
draft_path = RAW / f"draft_{year}.csv"
url = f"{BASE}/draft/NBA_{year}.html"
print(f"[{year}] draft page {url}")
time.sleep(SLEEP_S)
html = get_html(session, url)
picks = parse_draft_table(html, year)
print(f"[{year}] {len(picks)} picks")
for i, row in enumerate(picks, 1):
slug = row["bbref_player_slug"]
if not slug:
row.update(
{
"high_school_finish": "",
"hs_city": "",
"hs_state": "",
"hs_raw": "",
"birth_place": "",
"hs_source": "missing_player_page",
}
)
continue
if slug in cache and not force:
hs = cache[slug]
else:
print(f" [{i}/{len(picks)}] player {row['player_name']} ({slug})")
time.sleep(SLEEP_S)
try:
ph = get_html(session, row["bbref_player_url"])
hs = parse_player_hs(ph)
hs["fetched"] = True
except requests.HTTPError as e:
hs = {
"high_school_finish": "",
"hs_city": "",
"hs_state": "",
"hs_raw": "",
"birth_place": "",
"error": str(e),
}
cache[slug] = hs
if i % 5 == 0:
save_cache(cache)
row["high_school_finish"] = hs.get("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", "")
row["hs_source"] = "basketball_reference_player_page"
fields = [
"draft_year",
"pick",
"round",
"player_name",
"nba_team",
"college_or_prior",
"high_school_finish",
"hs_city",
"hs_state",
"hs_raw",
"birth_place",
"bbref_player_url",
"bbref_player_slug",
"hs_source",
]
with draft_path.open("w", newline="", encoding="utf-8") as f:
w = csv.DictWriter(f, fieldnames=fields, extrasaction="ignore")
w.writeheader()
w.writerows(picks)
print(f"[{year}] wrote {draft_path}")
return picks
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--years", default="2016-2025", help="e.g. 2016-2025 or 2022,2023")
ap.add_argument("--force", action="store_true", help="refetch player pages even if cached")
args = ap.parse_args()
years = parse_years(args.years)
RAW.mkdir(parents=True, exist_ok=True)
cache = load_cache()
session = requests.Session()
session.headers.update({"User-Agent": UA, "Accept-Language": "en-US,en;q=0.9"})
for year in years:
fetch_year(session, year, cache, force=args.force)
save_cache(cache)
print("done")
if __name__ == "__main__":
main()
|