dharits3's picture
v0.1.0: 656-pick panel 2016-2026, codebook, coverage, analysis notes, build scripts
e94c8f8 verified
Raw
History Blame Contribute Delete
9.58 kB
#!/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()