Spaces:
Sleeping
Sleeping
File size: 3,536 Bytes
3f31583 | 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 | """Scrape web tutorial sources and save as plain-text files in data/web/.
Uses requests + BeautifulSoup to extract readable text from each URL defined
as a tutorial/course source in CANONICAL_TEXT_SOURCES. Skips files that already
exist — safe to re-run.
Requires: pip install beautifulsoup4 (added to requirements/pyproject.toml separately)
Usage:
uv run python scripts/fetch_web_sources.py
"""
from __future__ import annotations
import sys
import time
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from rich.console import Console
from rich.table import Table
from researchpath.corpus import CANONICAL_TEXT_SOURCES
console = Console()
ROOT = Path(__file__).resolve().parents[1]
WEB_DIR = ROOT / "data" / "web"
WEB_DIR.mkdir(parents=True, exist_ok=True)
HEADERS = {
"User-Agent": (
"Mozilla/5.0 (compatible; ResearchPath/1.0; educational corpus builder)"
)
}
TIMEOUT = 30
def _fetch_text(url: str) -> str:
"""Fetch URL and return cleaned plain text via BeautifulSoup."""
import requests
from bs4 import BeautifulSoup
resp = requests.get(url, headers=HEADERS, timeout=TIMEOUT)
resp.raise_for_status()
# Force UTF-8 — prevents ¶ artifacts from latin-1 mis-detection
resp.encoding = "utf-8"
soup = BeautifulSoup(resp.text, "html.parser")
# Remove nav, footer, header, scripts, style blocks
for tag in soup.find_all(["nav", "footer", "header", "script", "style", "aside"]):
tag.decompose()
# Prefer main content areas in priority order
for selector in ["article", "main", '[role="main"]', ".content", "#content", "body"]:
container = soup.select_one(selector)
if container:
break
if container is None:
container = soup
lines = []
for element in container.find_all(["h1", "h2", "h3", "h4", "p", "li", "pre", "code"]):
text = element.get_text(" ", strip=True)
if text:
lines.append(text)
return "\n\n".join(lines)
def main() -> int:
try:
import requests # noqa: F401
from bs4 import BeautifulSoup # noqa: F401
except ImportError:
console.print(
"[red]Missing dependencies. Run:[/red]\n"
" uv add beautifulsoup4 requests"
)
return 1
web_sources = [
s for s in CANONICAL_TEXT_SOURCES
if s.filename.endswith(".txt")
]
table = Table(title="Web scrape results")
table.add_column("Source ID", style="bold")
table.add_column("Status")
table.add_column("Detail")
ok = 0
for source in web_sources:
dest = WEB_DIR / source.filename
if dest.exists():
chars = dest.stat().st_size
table.add_row(source.source_id, "[green]OK[/green]", f"already exists ({chars:,} chars)")
ok += 1
continue
try:
text = _fetch_text(source.url)
dest.write_text(text, encoding="utf-8")
table.add_row(source.source_id, "[green]OK[/green]", f"scraped {len(text):,} chars")
ok += 1
except Exception as e:
table.add_row(source.source_id, "[red]FAIL[/red]", str(e)[:80])
time.sleep(2) # polite crawl delay
console.print(table)
console.print(
f"\n[bold]{'[green]' if ok == len(web_sources) else '[yellow]'}"
f"{ok}/{len(web_sources)} web sources saved to data/web/[/bold]"
)
return 0 if ok > 0 else 1
if __name__ == "__main__":
sys.exit(main())
|