Spaces:
Sleeping
Sleeping
File size: 4,602 Bytes
122f5b9 | 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 | """
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()
|