""" station_scraper.py Scrapes ski station operational data for the three northern Spain stations managed by the government of Asturias/León: - Valgrande-Pajares (station_id: pajares) - San Isidro (station_id: sanisidro) - Fuentes de Invierno(station_id: fuentes) Primary source: infonieve.es (https://www.infonieve.es/estacion-esqui/{slug}/) Fallback: returns None values with a logged warning when scraping fails. Raw responses are saved to: data/raw/station_{station_id}_{date}.json """ import json import logging import re from datetime import date from pathlib import Path from typing import Optional import requests import yaml from bs4 import BeautifulSoup logger = logging.getLogger(__name__) # --------------------------------------------------------------------------- # Constants # --------------------------------------------------------------------------- _PROJECT_ROOT = Path(__file__).resolve().parent.parent _CONFIG_PATH = _PROJECT_ROOT / "config" / "stations.yaml" _RAW_DATA_DIR = _PROJECT_ROOT / "data" / "raw" _USER_AGENT = ( "Mozilla/5.0 (X11; Linux x86_64) " "AppleWebKit/537.36 (KHTML, like Gecko) " "Chrome/120.0.0.0 Safari/537.36" ) _REQUEST_TIMEOUT = 15 # seconds # Mapping from station_id to the slug used on infonieve.es _INFONIEVE_SLUGS: dict[str, str] = { "pajares": "valgrande-pajares", "sanisidro": "san-isidro", "fuentes": "fuentes-de-invierno", } # Known snow quality label normalisations (infonieve uses Spanish) _QUALITY_TRANSLATIONS: dict[str, str] = { "polvo": "powder", "nieve polvo": "powder", "granulada": "granular", "nieve granulada": "granular", "compacta": "compact", "nieve compacta": "compact", "helada": "icy", "nieve helada": "icy", "húmeda": "wet", "nieve húmeda": "wet", "primaveral": "spring", "nieve primaveral": "spring", "artificial": "artificial", "nieve artificial": "artificial", } # --------------------------------------------------------------------------- # Helpers # --------------------------------------------------------------------------- def _load_config() -> dict: """Load station configuration from stations.yaml.""" with open(_CONFIG_PATH, encoding="utf-8") as fh: return yaml.safe_load(fh) def _get_session() -> requests.Session: """Return a requests Session with a browser-like User-Agent.""" session = requests.Session() session.headers.update( { "User-Agent": _USER_AGENT, "Accept-Language": "es-ES,es;q=0.9,en;q=0.8", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", } ) return session def _save_raw(station_id: str, payload: dict) -> None: """Persist raw scraped payload to data/raw/ as JSON.""" _RAW_DATA_DIR.mkdir(parents=True, exist_ok=True) today = date.today().isoformat() filename = _RAW_DATA_DIR / f"station_{station_id}_{today}.json" try: with open(filename, "w", encoding="utf-8") as fh: json.dump(payload, fh, ensure_ascii=False, indent=2) logger.debug("Raw data saved to %s", filename) except OSError as exc: logger.warning("Could not save raw data for %s: %s", station_id, exc) def _parse_float(text: Optional[str]) -> Optional[float]: """Extract the first float-like value from a string, or return None.""" if not text: return None match = re.search(r"[\d]+[.,]?[\d]*", text.replace(",", ".")) if match: try: return float(match.group().replace(",", ".")) except ValueError: pass return None def _parse_int(text: Optional[str]) -> Optional[int]: """Extract the first integer value from a string, or return None.""" value = _parse_float(text) return int(value) if value is not None else None def _normalise_quality(raw: Optional[str]) -> Optional[str]: """Normalise a Spanish snow quality label to a short English keyword.""" if not raw: return None key = raw.strip().lower() return _QUALITY_TRANSLATIONS.get(key, raw.strip()) def _empty_record(station_id: str) -> dict: """Return a record with all operational fields set to None.""" return { "station_id": station_id, "date": date.today().isoformat(), "open_status": None, "km_open": None, "lifts_open": None, "snow_depth": None, "snow_quality": None, } # --------------------------------------------------------------------------- # Infonieve parser # --------------------------------------------------------------------------- def _fetch_infonieve_page(slug: str, session: requests.Session) -> Optional[BeautifulSoup]: """ Fetch and parse the infonieve.es station page. Returns a BeautifulSoup tree on success, None on any network or HTTP error. """ url = f"https://www.infonieve.es/estacion-esqui/{slug}/" try: response = session.get(url, timeout=_REQUEST_TIMEOUT) response.raise_for_status() return BeautifulSoup(response.text, "lxml") except requests.exceptions.Timeout: logger.warning("Timeout fetching infonieve page for slug '%s'", slug) except requests.exceptions.HTTPError as exc: logger.warning("HTTP error fetching infonieve page for slug '%s': %s", slug, exc) except requests.exceptions.RequestException as exc: logger.warning("Request error fetching infonieve page for slug '%s': %s", slug, exc) return None def _parse_infonieve(soup: BeautifulSoup, station_id: str) -> dict: """Extract operational fields from a parsed infonieve.es page. Infonieve uses a layout with keywords (Remontes, Kilómetros, Nieve) followed by ``value/total`` patterns. This parser works on the flattened page text with regex to be resilient to minor HTML restructuring. All fields default to None when the value cannot be reliably extracted. """ record = _empty_record(station_id) page_text = soup.get_text(separator=" ") # --- open_status --- # Look for Abierta or Cerrada status_tag = soup.find("strong", string=re.compile(r"abierta|cerrada", re.I)) if status_tag: label = status_tag.get_text(strip=True).lower() record["open_status"] = "abierta" in label else: # Fallback: scan page text text_lower = page_text.lower() if "abierta" in text_lower: record["open_status"] = True elif "cerrada" in text_lower: record["open_status"] = False # --- lifts_open --- # Pattern: "Remontes" ... N/M lifts_match = re.search( r"Remontes\s*(\d+)\s*/\s*(\d+)", page_text, re.I, ) if lifts_match: record["lifts_open"] = int(lifts_match.group(1)) logger.debug("Parsed lifts_open=%s (total=%s)", lifts_match.group(1), lifts_match.group(2)) # --- km_open --- # Pattern: "Kilómetros" ... N,NN/M,MM km_match = re.search( r"(?:Kil[óo]metros|Km)\s*([\d]+[.,]?\d*)\s*/\s*([\d]+[.,]?\d*)", page_text, re.I, ) if km_match: record["km_open"] = float(km_match.group(1).replace(",", ".")) logger.debug("Parsed km_open=%s (total=%s)", km_match.group(1), km_match.group(2)) # --- snow_depth --- # Pattern: "Nieve" ... N cm snow_match = re.search( r"Nieve\s*(\d+)\s*cm", page_text, re.I, ) if snow_match: record["snow_depth"] = int(snow_match.group(1)) logger.debug("Parsed snow_depth=%s cm", snow_match.group(1)) # --- snow_quality --- # Pattern: "Calidad" or "Tipo de nieve" followed by text quality_match = re.search( r"(?:calidad|tipo)\s+(?:de\s+)?(?:la\s+)?nieve[:\s]+([a-záéíóúñü]+)", page_text, re.I, ) if quality_match: record["snow_quality"] = _normalise_quality(quality_match.group(1)) return record # --------------------------------------------------------------------------- # Public scraper class # --------------------------------------------------------------------------- class StationScraper: """ Scrapes operational status data for the three Asturias/León ski stations. Usage ----- >>> scraper = StationScraper() >>> record = scraper.scrape_station("pajares") >>> all_records = scraper.scrape_all_stations() The scraper attempts to collect data from infonieve.es. When a page cannot be fetched or parsed, it logs a warning and returns a record with None values so that the rest of the pipeline can continue. """ def __init__(self) -> None: config = _load_config() self._stations: dict = config.get("stations", {}) self._session: requests.Session = _get_session() # ------------------------------------------------------------------ # Public API # ------------------------------------------------------------------ def scrape_station(self, station_id: str) -> dict: """ Scrape operational data for a single station. Parameters ---------- station_id: One of the keys defined in config/stations.yaml (e.g. 'pajares', 'sanisidro', 'fuentes'). Returns ------- dict with keys: station_id (str) date (str, ISO-8601) open_status (bool or None) km_open (float or None) lifts_open (int or None) snow_depth (int or None, centimetres) snow_quality(str or None) """ if station_id not in self._stations: logger.error( "Unknown station_id '%s'. Known stations: %s", station_id, list(self._stations.keys()), ) return _empty_record(station_id) logger.info("Scraping station: %s", station_id) record = self._scrape_infonieve(station_id) _save_raw(station_id, record) return record def scrape_all_stations(self) -> list[dict]: """ Scrape operational data for all stations defined in stations.yaml. Returns ------- List of dicts, one per station, in the same format as scrape_station(). """ results = [] for station_id in self._stations: record = self.scrape_station(station_id) results.append(record) return results # ------------------------------------------------------------------ # Internal scraping logic # ------------------------------------------------------------------ def _scrape_infonieve(self, station_id: str) -> dict: """ Attempt to scrape from infonieve.es and return an operational record. Falls back to an empty record (all fields None) when the page cannot be fetched or the content does not match expected patterns. """ slug = _INFONIEVE_SLUGS.get(station_id) if slug is None: logger.warning( "No infonieve.es slug configured for station '%s'. " "Returning empty record.", station_id, ) return _empty_record(station_id) soup = _fetch_infonieve_page(slug, self._session) if soup is None: logger.warning( "Could not fetch infonieve.es page for '%s' (slug: '%s'). " "All fields will be None. Check network connectivity or " "whether the URL has changed.", station_id, slug, ) return _empty_record(station_id) try: record = _parse_infonieve(soup, station_id) except Exception as exc: # pylint: disable=broad-except logger.warning( "Unexpected error parsing infonieve.es page for '%s': %s. " "Returning empty record.", station_id, exc, exc_info=True, ) return _empty_record(station_id) self._log_record_summary(record) return record # ------------------------------------------------------------------ # Utilities # ------------------------------------------------------------------ @staticmethod def _log_record_summary(record: dict) -> None: """Emit a one-line summary of the scraped record at INFO level.""" status_label = ( "OPEN" if record["open_status"] is True else "CLOSED" if record["open_status"] is False else "UNKNOWN" ) logger.info( "[%s] %s | km=%-5s lifts=%-3s depth=%-4s quality=%s", record["station_id"], status_label, record["km_open"], record["lifts_open"], record["snow_depth"], record["snow_quality"], ) # --------------------------------------------------------------------------- # CLI entry-point (for manual testing / cron scripts) # --------------------------------------------------------------------------- if __name__ == "__main__": logging.basicConfig( level=logging.INFO, format="%(asctime)s %(levelname)-8s %(name)s - %(message)s", ) scraper = StationScraper() records = scraper.scrape_all_stations() print(json.dumps(records, indent=2, ensure_ascii=False))