| import re |
| import csv |
| import time |
| import json |
| import random |
| import sys |
| import html as html_lib |
| from urllib.request import Request, urlopen |
| from urllib.parse import urlparse, parse_qs |
|
|
| |
| BASE_URL = "https://tnc-platform.web.app" |
| SITEMAP_URL = f"{BASE_URL}/sitemap.xml" |
| USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36" |
| |
| FIRESTORE_API_KEY = "AIzaSyA5AUOLUfpZ9VE0zWhi8-hF7t48_5wnT0s" |
| FIRESTORE_BASE_URL = "https://firestore.googleapis.com/v1/projects/tnc-platform/databases/(default)/documents/archive" |
|
|
| CSV_FILE = "tnc_seminars.csv" |
| JSONL_FILE = "tnc_seminars.jsonl" |
|
|
| def fetch_url(url): |
| """Fetches URL content with a custom User-Agent.""" |
| try: |
| req = Request(url, headers={"User-Agent": USER_AGENT}) |
| with urlopen(req, timeout=15) as response: |
| return response.read().decode("utf-8", errors="replace") |
| except Exception as e: |
| print(f"Error fetching {url}: {e}", file=sys.stderr) |
| return "" |
|
|
| def get_full_description(course_id): |
| """Fetches the full description directly from Firestore REST API.""" |
| api_url = f"{FIRESTORE_BASE_URL}/{course_id}?key={FIRESTORE_API_KEY}" |
| raw_json = fetch_url(api_url) |
| if not raw_json: |
| return "" |
| |
| try: |
| data = json.loads(raw_json) |
| |
| desc = data.get("fields", {}).get("description", {}).get("stringValue", "") |
| |
| |
| if desc.upper().startswith("DESCRIPTION:"): |
| desc = desc[len("DESCRIPTION:"):].strip() |
| |
| |
| desc = html_lib.unescape(desc) |
| |
| desc = re.sub(r'<[^>]+>', '', desc) |
| |
| return desc.strip() |
| except Exception as e: |
| print(f"Error parsing Firestore data for {course_id}: {e}", file=sys.stderr) |
| return "" |
|
|
| def clean_title(title): |
| """Removes the branding suffix from the title.""" |
| for sep in [" — ", " – ", " - "]: |
| if sep in title: |
| title = title.split(sep)[0] |
| return html_lib.unescape(title.strip()) |
|
|
| def main(): |
| print("Discovering seminars from sitemap...", file=sys.stderr) |
| sitemap_xml = fetch_url(SITEMAP_URL) |
| |
| |
| |
| course_urls = re.findall(r'<loc>(https://tnc-platform.web.app/archive/course.html\?id=(\d+))</loc>', sitemap_xml) |
| |
| |
| seen_ids = set() |
| unique_courses = [] |
| for url, cid in course_urls: |
| if cid not in seen_ids: |
| seen_ids.add(cid) |
| unique_courses.append((url, cid)) |
| |
| unique_courses.sort(key=lambda x: x[1], reverse=True) |
| print(f"Discovered {len(unique_courses)} seminars.", file=sys.stderr) |
|
|
| if not unique_courses: |
| print("No seminar URLs found in sitemap.", file=sys.stderr) |
| return |
|
|
| |
| with open(CSV_FILE, "w", encoding="utf-8", newline="") as f_csv, \ |
| open(JSONL_FILE, "w", encoding="utf-8") as f_jsonl: |
| |
| writer = csv.writer(f_csv) |
| writer.writerow(["Seminar Title", "Seminar Description"]) |
|
|
| for i, (url, cid) in enumerate(unique_courses, 1): |
| print(f"[{i}/{len(unique_courses)}] Scraping: {cid}", file=sys.stderr) |
| |
| |
| html_text = fetch_url(url) |
| title = "Unknown" |
| if html_text: |
| title_match = re.search(r"<title>(.*?)</title>", html_text, re.S | re.I) |
| title = clean_title(title_match.group(1)) if title_match else "Unknown" |
|
|
| |
| desc = get_full_description(cid) |
|
|
| if title or desc: |
| |
| writer.writerow([title, desc]) |
| f_csv.flush() |
| |
| |
| json_row = json.dumps({"title": title, "description": desc}, ensure_ascii=False) |
| f_jsonl.write(json_row + "\n") |
| f_jsonl.flush() |
|
|
| |
| time.sleep(random.uniform(0.1, 0.3)) |
|
|
| print(f"\nSuccess! Full dataset saved to:", file=sys.stderr) |
| print(f" - {CSV_FILE}", file=sys.stderr) |
| print(f" - {JSONL_FILE}", file=sys.stderr) |
|
|
| if __name__ == "__main__": |
| main() |
|
|