SPB Git

Repository Public

location_saguenay.py 11.9 KB 292 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/location_saguenay.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0913# Last Modified    : 2026-09-0814#15# =============================================================================16# AUTHOR & PROFESSIONAL AFFILIATION17# =============================================================================18#19# Author           : Simon-Pierre Boucher20# Position         : Professor of Finance21# Institution      : Université du Québec en Outaouais (UQO)22# Department       : Département des sciences administratives23# Organization     : SP Boucher24#25# Website          : https://spboucher.ai26# Git              : https://git.spboucher.ai27#28# =============================================================================29# OFFICIAL CONTACT DIRECTORY30# =============================================================================31#32# General          : info@spboucher.ai33# Professional     : contact@spboucher.ai34# Direct           : simon@spboucher.ai35# Research         : research@spboucher.ai36# Development      : dev@spboucher.ai37# Support          : support@spboucher.ai38# Security/Admin   : admin@spboucher.ai39# Notifications    : notifications@spboucher.ai40#41# Preferred Contact: contact@spboucher.ai42#43# =============================================================================44# COPYRIGHT & INTELLECTUAL PROPERTY45# =============================================================================46#47# Copyright (c) 202648# Simon-Pierre Boucher49#50# All rights reserved where applicable.51#52# This file is governed by the applicable project license,53# copyright notices, institutional agreements and relevant law.54#55# Unless expressly authorized by the applicable license or56# rights holder, copying, redistribution, sublicensing,57# publication and commercial exploitation are not permitted.58#59# Existing third-party rights and notices remain unaffected.60#61# =============================================================================62# CONFIDENTIALITY & SECURITY63# =============================================================================64#65# Classification   : Public66# Distribution     : Public repository; use is governed by the project license67# Security Contact : admin@spboucher.ai68#69# Access to this source does not independently grant permission70# to redistribute or disclose confidential materials.71#72# Do not embed credentials, private keys, access tokens,73# certificates or confidential personal information.74#75# =============================================================================76# LICENSE & MAINTENANCE77# =============================================================================78#79# License          : None specified (no license file in this repository)80# Maintainer       : Simon-Pierre Boucher81# Technical Contact: dev@spboucher.ai82#83# =============================================================================84# END OF SP BOUCHER SOURCE HEADER85# =============================================================================8687# -----------------------------------------------------------------------------88# Lou-Ka — Agrégateur de logements à louer (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# connectors/location_saguenay.py : connecteur Location Saguenay91#   (locationsaguenay.com — Saguenay : Chicoutimi près de l'UQAC/Cégep et92#   Jonquière près du Cégep ; propriétaire-gestionnaire, formule de base ou93#   tout inclus). WordPress classique (thème Davis), tout rendu serveur : le94#   menu « Logements disponibles » liste TOUTES les fiches, groupées par95#   « Appartements N chambres » (les pages villes /appartement-a-louer-96#   chicoutimi|jonquiere/ sont des vitrines SEO sans cartes). Une fiche WP par97#   immeuble/type d'unité (granularité immeuble, précédent immeubles_guillot) :98#   description libre et galerie photoswipe ; prix « sur demande » (aucun prix99#   publié -> price = None) et pas de dates de disponibilité.100#   ⚠️ robots.txt : Crawl-delay: 10 -> request_delay = 10 s et budget de fiches101#   réduit (max_details = 12, complété au fil des syncs par le cache BD).102# -----------------------------------------------------------------------------103from __future__ import annotations104105import hashlib106import re107import time108109from bs4 import BeautifulSoup110111from ..schema import Listing, normalize_unit_type, strip_accents112from .base import BaseConnector113114BASE = "https://locationsaguenay.com"115LIST_URL = f"{BASE}/"116117_GROUP_RE = re.compile(r"Appartements?\s+(\d+)\s+chambres?", re.I)118_ADDR_RE = re.compile(r"^\s*(\d[\w\s'’.,-]*?)\s*(?:à\s+\w[\w-]*)?\s*$")119120121class LocationSaguenayConnector(BaseConnector):122    source_id = "location_saguenay"123    request_delay = 10.0   # Crawl-delay: 10 du robots.txt — respecté tel quel124    max_details = 12       # garde-fou fiches détail (vraies requêtes par sync)125126    def fetch(self) -> list[Listing]:127        # Un raté transitoire (page 200 sans le menu « Logements disponibles »,128        # vu 2026-08-29) produisait un faux « 0 trouvé ok » : retry court, puis129        # erreur franche plutôt qu'un zéro silencieux. Le throttling de get()130        # (10 s) espace naturellement les essais.131        # Vu 2026-09-08 : le site cache ses pages (cache-control max-age=600,132        # vary: User-Agent) — une variante partielle figée pour notre UA fait133        # échouer les 3 essais sur la MÊME copie. Les essais 2 et 3 passent134        # donc un cache-buster pour forcer un rendu frais (pattern brio).135        for attempt in range(3):136            params = {"lkb": int(time.time())} if attempt else None137            html = self.get(LIST_URL, params=params).text138            soup = BeautifulSoup(html, "html.parser")139            root = self._find_menu_root(soup)140            if root is not None:141                break142        else:143            raise RuntimeError(144                "menu « Logements disponibles » introuvable après 3 essais")145146        self._fetched = 0147        listings: dict[str, Listing] = {}148        # groupes « Appartements N chambres », chacun avec ses fiches149        for group in root.find_all("li", recursive=False):150            head = group.find("a", recursive=False)151            label = head.get_text(strip=True) if head else ""152            m = _GROUP_RE.search(label)153            bedrooms = m.group(1) if m else ""154            sub = group.find("ul", class_="sub-menu")155            if sub is None:156                continue157            for a in sub.select("li > a[href]"):158                try:159                    self._parse_entry(a, bedrooms, listings)160                except Exception:161                    continue162        return list(listings.values())163164    @staticmethod165    def _find_menu_root(soup: BeautifulSoup):166        """Sous-menu de l'entrée « Logements disponibles » du menu principal."""167        menu = soup.select_one("ul.blog-menu")168        if menu is None:169            return None170        for li in menu.find_all("li", recursive=False):171            a = li.find("a", recursive=False)172            if a and "logements disponibles" in a.get_text(strip=True).lower():173                return li.find("ul", class_="sub-menu")174        return None175176    # -- entrée du menu (une fiche WP par immeuble/type) -------------------------------177    def _parse_entry(self, a, bedrooms: str,178                     listings: dict[str, Listing]) -> None:179        url = a["href"]180        if not url.startswith(BASE):181            return182        slug = url.rstrip("/").rsplit("/", 1)[-1]183        if not slug or slug in listings:184            return185        title = re.sub(r"\s+", " ", a.get_text(" ", strip=True))186187        # type : nombre de chambres du groupe du menu (Loft si le titre le dit)188        if re.search(r"\bLofts?\b", title, re.I):189            unit_type = "Loft"190        elif bedrooms:191            unit_type = normalize_unit_type(f"{bedrooms} chambres")192        else:193            unit_type = ""194195        # adresse civique en tête de titre (« 2603, rue St-Hubert à Jonquière : … »)196        address = ""197        head = title.split(":", 1)[0].strip()198        if re.match(r"^\d", head):199            address = re.sub(r"\s+à\s+\w[\w'’-]*$", "", head).strip(" ,")200201        # secteur : mots-clés factuels du titre (UQAC = Chicoutimi)202        key = strip_accents(title.lower())203        sector = ""204        if "jonquiere" in key:205            sector = "Jonquière"206        elif "chicoutimi" in key or "uqac" in key:207            sector = "Chicoutimi"208209        amenities = []210        if bedrooms:211            amenities.append(f"{bedrooms} chambre(s)")212213        lst = Listing(214            source=self.source_id,215            external_id=slug,216            url=url,217            title=title,218            address=address,219            sector=sector,220            city="Saguenay",221            unit_type=unit_type,222            amenities=amenities,223            images=[],224        )225226        key_hash = hashlib.sha1(f"{title}|{bedrooms}".encode("utf-8")).hexdigest()227        try:228            payload = self.detail(slug, key_hash,229                                  lambda u=url: self._fetch_detail(u))230            self._apply_detail(lst, payload)231        except Exception:232            pass233        listings[slug] = lst234235    # -- fiche détail (page WP de l'immeuble) ------------------------------------------236    def _fetch_detail(self, url: str) -> dict:237        """Description libre, mention de prix (« sur demande ») et galerie."""238        if self._fetched >= self.max_details:239            raise RuntimeError("budget de fiches détail atteint")240        self._fetched += 1241        html = self.get(url).text242        soup = BeautifulSoup(html, "html.parser")243        out: dict = {}244245        content = soup.select_one(".entry-content") or soup246        paras: list[str] = []247        for p in content.find_all("p"):248            txt = re.sub(r"\s+", " ", p.get_text(" ", strip=True))249            if not txt:250                continue251            # mention de prix du site (« Tarif/Prix sur demande ») : libellé brut252            m = re.search(r"(?:tarif|prix)[^.]*demande[^.]*\.?", txt, re.I)253            if m:254                out.setdefault("price_label", m.group(0).strip())255                continue256            # fin du contenu utile : bloc contact/formulaire257            if re.search(r"contactez|formulaire|courriel|581-|1-888-", txt, re.I):258                break259            paras.append(txt)260        if paras:261            out["description"] = "\n".join(paras)[:1500]262263        # secteur si la description est plus précise que le titre264        key = strip_accents(" ".join(paras).lower())265        if "jonquiere" in key:266            out["sector"] = "Jonquière"267        elif "chicoutimi" in key or "uqac" in key:268            out["sector"] = "Chicoutimi"269270        # galerie photoswipe (photos réelles ; logo du site exclu)271        images: list[str] = []272        for img in content.find_all("img", src=True):273            u = img["src"]274            if (u.startswith("http") and "/wp-content/uploads/" in u275                    and "cropped-" not in u and u not in images):276                images.append(u)277        out["images"] = images[:25]278        return out279280    def _apply_detail(self, lst: Listing, d: dict) -> None:281        """Reporte le payload (frais ou en cache) sur l'annonce."""282        if not d:283            return284        if d.get("description"):285            lst.description = d["description"]286        if d.get("price_label"):287            lst.price_label = d["price_label"]      # « sur demande » : prix None288        if d.get("sector") and not lst.sector:289            lst.sector = d["sector"]290        if d.get("images"):291            lst.images = d["images"]292
Files main
Menu

Theme