"""Fetch one provider pricing page as text, only if robots.txt allows it. At most 1 request per second. Pages go to intern/pages/ for a human-style read; only extracted facts go into data/free_tiers.csv.""" import html import pathlib import re import sys import time import urllib.parse import urllib.request import urllib.robotparser UA = "free-tier-dataset/0.1 (+mailto:novusops@mail.grokbot.com)" ROOT = pathlib.Path(__file__).resolve().parent.parent def allowed(url): p = urllib.parse.urlparse(url) rp = urllib.robotparser.RobotFileParser() rp.set_url(f"{p.scheme}://{p.netloc}/robots.txt") try: req = urllib.request.Request(rp.url, headers={"User-Agent": UA}) with urllib.request.urlopen(req, timeout=20) as r: rp.parse(r.read().decode(errors="ignore").splitlines()) except Exception: rp.parse([]) # no robots.txt reachable: treat as no rules time.sleep(1) return rp.can_fetch(UA, url) def to_text(raw): raw = re.sub(r"(?is)<(script|style|noscript|svg)[^>]*>.*?", " ", raw) raw = re.sub(r"(?s)<[^>]+>", " ", raw) return re.sub(r"\s+", " ", html.unescape(raw)) def fetch(pid, url): if not allowed(url): print(f"{pid}: robots.txt disallows {url}, skipped") return None req = urllib.request.Request(url, headers={"User-Agent": UA}) with urllib.request.urlopen(req, timeout=30) as r: txt = to_text(r.read().decode(errors="ignore")) (ROOT / "intern" / "pages" / f"{pid}.txt").write_text(txt) time.sleep(1) print(f"{pid}: {len(txt)} chars") return txt if __name__ == "__main__": fetch(sys.argv[1], sys.argv[2])