| |
| """ |
| scrape_reviews.py — Fetch the RocketReviews.com review index and scrape each |
| detail page, saving structured JSON to source/reviews/. |
| |
| Output |
| ------ |
| source/reviews/index.jsonl one record per review (raw index fields) |
| source/reviews/detail/{id}.json full parsed detail per review |
| |
| Usage |
| ----- |
| python scripts/scrape_reviews.py |
| python scripts/scrape_reviews.py --delay 2.0 --limit 10 |
| python scripts/scrape_reviews.py --force # re-scrape existing files |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import json |
| import logging |
| import re |
| import sys |
| import time |
| from datetime import datetime, timezone |
| from pathlib import Path |
| from typing import Optional |
|
|
| import requests |
| from bs4 import BeautifulSoup, NavigableString, Tag |
| from requests.adapters import HTTPAdapter |
| from urllib3.util.retry import Retry |
|
|
| |
| |
| |
|
|
| BASE_URL = "https://www.rocketreviews.com" |
| INDEX_URL = f"{BASE_URL}/data/reviews/reviews.php" |
| USER_AGENT = "RocketReviews-Dataset/1.0" |
| DEFAULT_DELAY = 1.0 |
|
|
| ROOT = Path(__file__).parent.parent.parent |
| SOURCE_DIR = ROOT / "source" / "reviews" |
| DETAIL_DIR = SOURCE_DIR / "detail" |
|
|
| |
| |
| |
|
|
| logging.basicConfig( |
| level=logging.INFO, |
| format="%(asctime)s %(levelname)s %(message)s", |
| handlers=[logging.StreamHandler(sys.stdout)], |
| ) |
| log = logging.getLogger(__name__) |
|
|
| |
| |
| |
|
|
|
|
| def _build_session() -> requests.Session: |
| s = requests.Session() |
| s.headers["User-Agent"] = USER_AGENT |
| retry = Retry( |
| total=3, |
| backoff_factor=2.0, |
| status_forcelist=[429, 500, 502, 503, 504], |
| allowed_methods=["GET"], |
| ) |
| s.mount("https://", HTTPAdapter(max_retries=retry)) |
| s.mount("http://", HTTPAdapter(max_retries=retry)) |
| return s |
|
|
|
|
| class RateLimiter: |
| def __init__(self, delay: float) -> None: |
| self.delay = delay |
| self._last: float = 0.0 |
|
|
| def wait(self) -> None: |
| elapsed = time.monotonic() - self._last |
| if elapsed < self.delay: |
| time.sleep(self.delay - elapsed) |
| self._last = time.monotonic() |
|
|
|
|
| |
| |
| |
|
|
|
|
| def _re_first(pattern: str, text: str, group: int = 1) -> Optional[str]: |
| m = re.search(pattern, text) |
| return m.group(group) if m else None |
|
|
|
|
| def _parse_rating_block(soup: BeautifulSoup, label: str) -> Optional[int]: |
| """ |
| Find '<strong>{label} Rating:</strong>' and count filled Material Icons |
| stars ('star') that follow it, excluding 'star_border' (empty stars). |
| """ |
| strong = soup.find("strong", string=re.compile(rf"^{label} Rating:?$", re.I)) |
| if not strong: |
| return None |
|
|
| |
| text = "" |
| for sib in strong.next_siblings: |
| if isinstance(sib, Tag) and sib.name == "strong": |
| break |
| text += sib.get_text() if isinstance(sib, Tag) else str(sib) |
|
|
| |
| filled = len(re.findall(r"\bstar\b(?!_border)", text)) |
| return filled if filled else None |
|
|
|
|
| def _parse_ratings(soup: BeautifulSoup) -> dict: |
| return { |
| "construction": _parse_rating_block(soup, "Construction"), |
| "flight": _parse_rating_block(soup, "Flight"), |
| "overall": _parse_rating_block(soup, "Overall"), |
| } |
|
|
|
|
| def _parse_product(soup: BeautifulSoup) -> dict: |
| html = str(soup) |
|
|
| |
| diameter_raw = _re_first(r"/kit-index-diameter-(\d+)\.html", html) |
| diameter = int(diameter_raw) / 10000 if diameter_raw else None |
|
|
| |
| length_raw = _re_first(r"/kit-index-length-(\d+)\.html", html) |
| length = int(length_raw) / 10000 if length_raw else None |
|
|
| |
| skill_raw = _re_first(r"/kit-index-skilllevel-(\d+)\.html", html) |
| skill = int(skill_raw) if skill_raw else None |
|
|
| |
| styles = [ |
| m.replace("-", " ").title() |
| for m in re.findall(r"/kit-index-style-([a-z][a-z-]*)-\d+\.html", html) |
| ] |
|
|
| |
| price_raw = _re_first(r"\$\s*(\d+(?:\.\d{1,2})?)", soup.get_text()) |
| price = float(price_raw) if price_raw else None |
|
|
| return { |
| "diameter_in": diameter, |
| "length_in": length, |
| "skill_level": skill, |
| "style": styles, |
| "price_usd": price, |
| } |
|
|
|
|
| |
| _SKIP_SECTION_RE = re.compile( |
| r"^\s*(flights?|.*reviews?|what you can do|sign in|create account)\s*$", |
| re.I, |
| ) |
|
|
|
|
| def _parse_sections(soup: BeautifulSoup) -> dict[str, str]: |
| """ |
| Walk all h2/h4 headings and collect the plain text that follows each one |
| until the next heading of the same or higher level. Skips headings that |
| correspond to data grids (flight logs, related reviews). |
| """ |
| sections: dict[str, str] = {} |
|
|
| for heading in soup.find_all(["h2", "h4"]): |
| title = heading.get_text(strip=True) |
| if not title or _SKIP_SECTION_RE.match(title): |
| continue |
|
|
| parts: list[str] = [] |
| for sib in heading.next_siblings: |
| if isinstance(sib, Tag) and sib.name in ("h2", "h4"): |
| break |
| if isinstance(sib, Tag): |
| text = sib.get_text(separator=" ", strip=True) |
| elif isinstance(sib, NavigableString): |
| text = str(sib).strip() |
| else: |
| continue |
| if text: |
| parts.append(text) |
|
|
| content = " ".join(parts).strip() |
| if content: |
| sections[title] = content |
|
|
| return sections |
|
|
|
|
| def _parse_detail(html: str, index_rec: dict) -> dict: |
| soup = BeautifulSoup(html, "lxml") |
|
|
| |
| canonical_path = _re_first(r'href=["\']?(/review-\d+\.html)', html) |
| canonical_url = f"{BASE_URL}{canonical_path}" if canonical_path else None |
|
|
| |
| alias_path = index_rec.get("url", "") |
| url_alias = f"{BASE_URL}{alias_path}" if alias_path else None |
|
|
| |
| |
| kit_id_raw = _re_first(r"Kit_ID&value=(-?\d+)", html) |
| kit_id_int = int(kit_id_raw) if kit_id_raw else None |
| kit_url = f"{BASE_URL}/product-{kit_id_int}.html" if kit_id_int and kit_id_int > 0 else None |
|
|
| |
| mfr_canonical = _re_first(r'href="(/[a-z][a-z0-9-]+-\d+\.html)"', html) |
| manufacturer_url = f"{BASE_URL}{mfr_canonical}" if mfr_canonical else None |
|
|
| |
| |
| mfr_alias = _re_first(r"(/kit-index-manufacturer-[^\"']+\.html)", html) |
| manufacturer_url_alias = f"{BASE_URL}{mfr_alias}" if mfr_alias else None |
|
|
| |
| manufacturer = index_rec.get("manufacturer") or None |
| mfr_link = soup.find("a", href=re.compile(r"/kit-index-manufacturer-")) |
| if mfr_link: |
| manufacturer = mfr_link.get_text(strip=True) or manufacturer |
|
|
| |
| |
| contributor_path = _re_first(r"(/[a-z][a-z0-9-]+-\d{4,}\.html)", html) |
| contributor_url = f"{BASE_URL}{contributor_path}" if contributor_path else None |
|
|
| return { |
| "id": int(index_rec["id"]), |
| "url": canonical_url, |
| "url_alias": url_alias, |
| "date": index_rec.get("date"), |
| "contributor": index_rec.get("contributor"), |
| "contributor_url": contributor_url, |
| "kit": index_rec.get("kit"), |
| "kit_url": kit_url, |
| "manufacturer": manufacturer, |
| "manufacturer_url": manufacturer_url, |
| "manufacturer_url_alias": manufacturer_url_alias, |
| "type": index_rec.get("type"), |
| "scraped_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), |
| "ratings": _parse_ratings(soup), |
| "product": _parse_product(soup), |
| "sections": _parse_sections(soup), |
| } |
|
|
|
|
| |
| |
| |
|
|
|
|
| def fetch_index(session: requests.Session) -> list[dict]: |
| log.info("Fetching review index from %s", INDEX_URL) |
| resp = session.get(INDEX_URL, timeout=30) |
| resp.raise_for_status() |
| records = resp.json().get("records", []) |
| log.info("Index returned %d records.", len(records)) |
| return records |
|
|
|
|
| def scrape_detail( |
| session: requests.Session, |
| rate: RateLimiter, |
| index_rec: dict, |
| force: bool = False, |
| ) -> Optional[dict]: |
| review_id = int(index_rec["id"]) |
| shard = f"{review_id // 1000:03d}" |
| shard_dir = DETAIL_DIR / shard |
| dest = shard_dir / f"{review_id:06d}.json" |
|
|
| if dest.exists() and not force: |
| log.debug("Already scraped %s, skipping.", review_id) |
| return None |
|
|
| alias_path = index_rec.get("url", "") |
| if not alias_path: |
| log.warning("No URL for review %s, skipping.", review_id) |
| return None |
|
|
| url = f"{BASE_URL}{alias_path}" |
| rate.wait() |
|
|
| try: |
| resp = session.get(url, timeout=30) |
| resp.raise_for_status() |
| except requests.RequestException as exc: |
| log.warning("Failed to fetch review %s: %s", review_id, exc) |
| return None |
|
|
| return _parse_detail(resp.text, index_rec) |
|
|
|
|
| |
| |
| |
|
|
|
|
| def main() -> None: |
| parser = argparse.ArgumentParser(description="Scrape RocketReviews.com reviews.") |
| parser.add_argument( |
| "--delay", |
| type=float, |
| default=DEFAULT_DELAY, |
| help=f"Seconds between requests (default: {DEFAULT_DELAY})", |
| ) |
| parser.add_argument( |
| "--limit", |
| type=int, |
| default=None, |
| help="Stop after scraping this many detail pages (useful for testing)", |
| ) |
| parser.add_argument( |
| "--force", |
| action="store_true", |
| help="Re-scrape reviews that already have a saved detail file", |
| ) |
| args = parser.parse_args() |
|
|
| SOURCE_DIR.mkdir(parents=True, exist_ok=True) |
| DETAIL_DIR.mkdir(parents=True, exist_ok=True) |
|
|
| session = _build_session() |
| rate = RateLimiter(args.delay) |
|
|
| |
| |
| |
| records = fetch_index(session) |
|
|
| scraped_at = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") |
| index_path = SOURCE_DIR / "index.jsonl" |
| with index_path.open("w", encoding="utf-8") as f: |
| for rec in records: |
| f.write(json.dumps({**rec, "scraped_at": scraped_at}) + "\n") |
| log.info("Wrote %d index records to %s", len(records), index_path) |
|
|
| |
| |
| |
| if args.limit: |
| records = records[: args.limit] |
|
|
| ok = skipped = failed = 0 |
| total = len(records) |
|
|
| for i, rec in enumerate(records, 1): |
| result = scrape_detail(session, rate, rec, force=args.force) |
|
|
| if result is None: |
| |
| skipped += 1 |
| continue |
|
|
| review_id = int(rec["id"]) |
| shard = f"{review_id // 1000:03d}" |
| shard_dir = DETAIL_DIR / shard |
| shard_dir.mkdir(parents=True, exist_ok=True) |
| dest = shard_dir / f"{review_id:06d}.json" |
| |
| try: |
| dest.write_text( |
| json.dumps(result, indent=2, ensure_ascii=False), encoding="utf-8" |
| ) |
| ok += 1 |
| log.debug("Saved %s", dest.name) |
| except OSError as exc: |
| log.warning("Could not write %s: %s", dest, exc) |
| failed += 1 |
|
|
| if i % 25 == 0 or i == total: |
| log.info( |
| "Progress: %d/%d — ok=%d skipped=%d failed=%d", |
| i, |
| total, |
| ok, |
| skipped, |
| failed, |
| ) |
|
|
| log.info("Done — ok=%d skipped=%d failed=%d", ok, skipped, failed) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|