Datasets:
File size: 13,367 Bytes
25c60c2 bb70d66 25c60c2 bb70d66 25c60c2 | 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 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 | #!/usr/bin/env python3
"""
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
# ---------------------------------------------------------------------------
# Config
# ---------------------------------------------------------------------------
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 # seconds between requests
ROOT = Path(__file__).parent.parent.parent
SOURCE_DIR = ROOT / "source" / "reviews"
DETAIL_DIR = SOURCE_DIR / "detail"
# ---------------------------------------------------------------------------
# Logging
# ---------------------------------------------------------------------------
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s",
handlers=[logging.StreamHandler(sys.stdout)],
)
log = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# HTTP session
# ---------------------------------------------------------------------------
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()
# ---------------------------------------------------------------------------
# Parsing helpers
# ---------------------------------------------------------------------------
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
# Collect raw text from siblings until the next <strong> tag
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)
# Count 'star' occurrences that are NOT 'star_border'
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: /kit-index-diameter-13260.html → 13260 / 10000 = 1.3260 inches
diameter_raw = _re_first(r"/kit-index-diameter-(\d+)\.html", html)
diameter = int(diameter_raw) / 10000 if diameter_raw else None
# Length: /kit-index-length-290000.html → 290000 / 10000 = 29.0000 inches
length_raw = _re_first(r"/kit-index-length-(\d+)\.html", html)
length = int(length_raw) / 10000 if length_raw else None
# Skill level: /kit-index-skilllevel-1.html → 1
skill_raw = _re_first(r"/kit-index-skilllevel-(\d+)\.html", html)
skill = int(skill_raw) if skill_raw else None
# Style: /kit-index-style-{name}-{id}.html — one or more values
styles = [
m.replace("-", " ").title()
for m in re.findall(r"/kit-index-style-([a-z][a-z-]*)-\d+\.html", html)
]
# Price: first dollar amount mentioned in the page text
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,
}
# Section headings that contain grids/tables rather than review text
_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 URL from any /review-{N}.html href in the page
canonical_path = _re_first(r'href=["\']?(/review-\d+\.html)', html)
canonical_url = f"{BASE_URL}{canonical_path}" if canonical_path else None
# Alias URL — slug URL from the index
alias_path = index_rec.get("url", "")
url_alias = f"{BASE_URL}{alias_path}" if alias_path else None
# Kit URL constructed from the Kit_ID in the JS data source
# e.g. data/flightlog/flights.php?column=Kit_ID&value=7163
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
# Manufacturer canonical URL: e.g. /estes-1093.html
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
# Manufacturer alias URL from the kit-index filter link
# e.g. /kit-index-manufacturer-estes.html
mfr_alias = _re_first(r"(/kit-index-manufacturer-[^\"']+\.html)", html)
manufacturer_url_alias = f"{BASE_URL}{mfr_alias}" if mfr_alias else None
# Manufacturer name from the kit-index link (more reliable than the index field)
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 URL from profile link with 4+ digit numeric suffix
# e.g. /darrell-ritchies-darrell-8979.html
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),
}
# ---------------------------------------------------------------------------
# Fetch helpers
# ---------------------------------------------------------------------------
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)
# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------
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)
# ------------------------------------------------------------------
# Step 1: fetch and write the full index
# ------------------------------------------------------------------
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)
# ------------------------------------------------------------------
# Step 2: scrape each detail page
# ------------------------------------------------------------------
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:
# Already exists and --force not set, or missing URL
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()
|