Spaces:
Sleeping
Sleeping
Download scripts/scrape_catalog.py from maddy1007/shl-recommender: direct link, hf CLI and curl.
- Browser
- Download file 4.6 kB
-
https://huggingface.co/spaces/maddy1007/shl-recommender/resolve/main/scripts/scrape_catalog.py
- Command line
-
hf download hf://spaces/maddy1007/shl-recommender/scripts/scrape_catalog.py
-
curl -L -o scrape_catalog.py https://huggingface.co/spaces/maddy1007/shl-recommender/resolve/main/scripts/scrape_catalog.py
4.6 kB
| """ | |
| SHL catalog scraper — fetches and updates assessment data. | |
| Run this script to refresh the local catalog: | |
| python scripts/scrape_catalog.py | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import logging | |
| import re | |
| import time | |
| from pathlib import Path | |
| from typing import List, Optional | |
| import httpx | |
| from bs4 import BeautifulSoup | |
| logger = logging.getLogger(__name__) | |
| logging.basicConfig(level=logging.INFO) | |
| CATALOG_URL = "https://www.shl.com/solutions/products/product-catalog/" | |
| OUTPUT_PATH = Path(__file__).parent.parent / "data" / "shl_catalog_scraped.json" | |
| def scrape_catalog_page( | |
| client: httpx.Client, | |
| start: int = 0, | |
| type_filter: int = 1, | |
| ) -> List[dict]: | |
| """Scrape a single page of the SHL catalog.""" | |
| url = f"{CATALOG_URL}?start={start}&type={type_filter}" | |
| try: | |
| resp = client.get(url, timeout=15.0) | |
| resp.raise_for_status() | |
| except Exception as e: | |
| logger.warning("Failed to fetch %s: %s", url, e) | |
| return [] | |
| soup = BeautifulSoup(resp.text, "html.parser") | |
| items = [] | |
| # SHL catalog uses table rows for product listings | |
| rows = soup.select("table tr") or soup.select(".product-item") or soup.select("[data-entity]") | |
| for row in rows: | |
| item = parse_catalog_row(row) | |
| if item: | |
| items.append(item) | |
| return items | |
| def parse_catalog_row(element) -> Optional[dict]: | |
| """Parse a single assessment row from the catalog page.""" | |
| try: | |
| # Extract name and URL | |
| link = element.find("a") | |
| if not link: | |
| return None | |
| name = link.get_text(strip=True) | |
| url = link.get("href", "") | |
| if not url.startswith("http"): | |
| url = f"https://www.shl.com{url}" | |
| if not name or len(name) < 3: | |
| return None | |
| # Extract type tags | |
| tags = [] | |
| tag_els = element.select(".shl-catalogue__tag, .assessment-tag, td span") | |
| for tag_el in tag_els: | |
| text = tag_el.get_text(strip=True) | |
| if text and len(text) < 40: | |
| tags.append(text) | |
| return { | |
| "name": name, | |
| "url": url, | |
| "raw_tags": tags, | |
| } | |
| except Exception as e: | |
| logger.debug("Parse error: %s", e) | |
| return None | |
| def enrich_from_detail_page(client: httpx.Client, item: dict) -> dict: | |
| """Fetch additional details from an assessment's detail page.""" | |
| url = item.get("url", "") | |
| if not url or "shl.com" not in url: | |
| return item | |
| try: | |
| resp = client.get(url, timeout=10.0) | |
| resp.raise_for_status() | |
| soup = BeautifulSoup(resp.text, "html.parser") | |
| # Extract description | |
| desc_el = ( | |
| soup.select_one("meta[name='description']") | |
| or soup.select_one(".hero__description") | |
| or soup.select_one(".product-description") | |
| ) | |
| if desc_el: | |
| item["description"] = ( | |
| desc_el.get("content", "") | |
| or desc_el.get_text(strip=True) | |
| )[:500] | |
| time.sleep(0.3) # Be polite | |
| except Exception as e: | |
| logger.debug("Detail page fetch error for %s: %s", url, e) | |
| return item | |
| def run_scrape() -> None: | |
| """Full catalog scrape with pagination.""" | |
| headers = { | |
| "User-Agent": ( | |
| "Mozilla/5.0 (compatible; SHL-Recommender-Bot/1.0; " | |
| "+https://github.com/bhartimadhav10/shl)" | |
| ) | |
| } | |
| all_items = [] | |
| with httpx.Client(headers=headers, follow_redirects=True) as client: | |
| # Type 1 = Individual Test Solutions | |
| for type_id in [1, 2]: | |
| for start in range(0, 500, 12): | |
| items = scrape_catalog_page(client, start=start, type_filter=type_id) | |
| if not items: | |
| logger.info("No more items at start=%d type=%d", start, type_id) | |
| break | |
| logger.info("Fetched %d items (start=%d, type=%d)", len(items), start, type_id) | |
| all_items.extend(items) | |
| time.sleep(0.5) | |
| # Deduplicate by URL | |
| seen_urls = set() | |
| unique_items = [] | |
| for item in all_items: | |
| url = item.get("url", "") | |
| if url not in seen_urls: | |
| seen_urls.add(url) | |
| unique_items.append(item) | |
| logger.info("Scraped %d unique assessments", len(unique_items)) | |
| # Save raw results | |
| OUTPUT_PATH.parent.mkdir(parents=True, exist_ok=True) | |
| OUTPUT_PATH.write_text(json.dumps(unique_items, indent=2, ensure_ascii=False)) | |
| logger.info("Saved to %s", OUTPUT_PATH) | |
| if __name__ == "__main__": | |
| run_scrape() | |