SPB Git

Repository Public

savouet.py 14.0 KB 355 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/savouet.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0913# Last Modified    : 2026-08-0914#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/savouet.py : connecteur Groupe Savouet (savouet.ca)91#   Gestionnaire-propriétaire de Sherbrooke (Fleurimont, Mont-Bellevue,92#   Centre-ville, Rock-Forest, Lennoxville) + East Angus. Webflow CMS rendu93#   serveur (même famille que copley.py) : page /logement, cartes94#   `a[href^=/logements-a-louer/]` avec champs étiquetés `fs-cmsfilter-field`95#   (prix, dimensions, secteur, atout/meublé, type) + bandeau `.rabais`96#   (« Libre dès maintenant ! »). Fiches détail via self.detail() (cache BD) :97#   blocs `.term-block-1` (étage, animaux, ameublement, stationnement, sdb,98#   typologie), description `.w-richtext`, galerie `img.cover-image`.99#   ATTENTION Webflow : les variantes conditionnelles `w-condition-invisible`100#   (valeurs masquées côté client) doivent être exclues partout.101# -----------------------------------------------------------------------------102from __future__ import annotations103104import hashlib105import json106import re107108from bs4 import BeautifulSoup109110from ..schema import Listing, normalize_unit_type, parse_price, strip_accents111from .base import BaseConnector112113BASE = "https://www.savouet.ca"114LIST_URL = f"{BASE}/logement"115116# image de remplacement Webflow « aucune photo »117_PLACEHOLDER_RE = re.compile(r"sans-photo|placeholder", re.I)118119120def _visible(el) -> bool:121    """Faux si l'élément (ou un parent proche) porte w-condition-invisible."""122    node = el123    for _ in range(4):124        if node is None or not getattr(node, "get", None):125            break126        if "w-condition-invisible" in (node.get("class") or []):127            return False128        node = node.parent129    return True130131132def _pets_value(raw: str) -> str | None:133    """« Non permis (chat toléré) » -> conditions ; « Non permis » -> non ;134    « Permis » -> oui ; sinon None (jamais deviné)."""135    k = strip_accents((raw or "").strip().lower())136    if not k:137        return None138    if "non permis" in k or k.startswith("non"):139        return "conditions" if re.search(r"tolere|chat|chien|sauf", k) else "non"140    if "permis" in k or "accepte" in k:141        return "oui"142    return None143144145def _furnished_value(raw: str) -> bool | None:146    """« Non meublé » -> False ; « Meublé » -> True ; « Semi meublé » -> None147    (état partiel : on garde le texte source dans les commodités)."""148    k = strip_accents((raw or "").strip().lower())149    if not k or "semi" in k:150        return None151    if k.startswith("non"):152        return False153    if "meuble" in k:154        return True155    return None156157158class SavouetConnector(BaseConnector):159    source_id = "savouet"160    request_delay = 0.6161    max_details = 60          # garde-fou : vraies requêtes de fiches détail162163    def fetch(self) -> list[Listing]:164        html = self.get(LIST_URL).text165        soup = BeautifulSoup(html, "html.parser")166167        listings: dict[str, Listing] = {}168        for card in soup.select('a[href^="/logements-a-louer/"]'):169            try:170                lst = self._parse_card(card)171            except Exception:172                continue173            if lst and lst.external_id not in listings:174                listings[lst.external_id] = lst175176        # fiches détail (cache BD) : étage, animaux, meublé, description, photos177        self._fetched = 0178        for lst in listings.values():179            key = hashlib.sha1(180                f"{lst.price_label}|{lst.availability}|{lst.unit_type}"181                .encode("utf-8")).hexdigest()182183            def fetch_fn(u=lst.url):184                if self._fetched >= self.max_details:185                    raise RuntimeError("budget de fiches détail atteint")186                self._fetched += 1187                return self._fetch_detail(u)188189            try:190                payload = self.detail(lst.external_id, key, fetch_fn)191            except Exception:192                continue193            self._apply_detail(lst, payload)194195        return list(listings.values())196197    # -- carte Webflow ------------------------------------------------------------198    def _parse_card(self, card) -> Listing | None:199        href = (card.get("href") or "").split("?")[0].rstrip("/")200        m = re.match(r"/logements-a-louer/([\w\-%.]+)$", href)201        if not m:202            return None203        slug = m.group(1)204205        title_el = card.select_one("h2.is-service-title")206        title = " ".join(title_el.get_text(" ", strip=True).split()) if title_el else ""207208        # hors périmètre logement : garages, stationnements, locaux209        if re.search(r"garage|stationnement|local|entrep[oô]t", title, re.I):210            return None211212        # champs étiquetés fs-cmsfilter-field (variantes invisibles exclues) ;213        # « secteur » sert deux fois : bandeau .rabais (disponibilité) + secteur214        fields: dict[str, list[str]] = {}215        availability = ""216        for el in card.select("[fs-cmsfilter-field]"):217            if not _visible(el):218                continue219            val = " ".join(el.get_text(" ", strip=True).split())220            if not val:221                continue222            if el.find_parent(class_="rabais") is not None:223                availability = availability or val224                continue225            fields.setdefault(el.get("fs-cmsfilter-field", ""), []).append(val)226227        sector = (fields.get("secteur") or [""])[0]228        price_label = (fields.get("prix") or [""])[0]229        unit_type = normalize_unit_type((fields.get("dimensions") or [""])[0])230        housing_type = (fields.get("type") or [""])[0]231        atout = (fields.get("atout") or [""])[0]          # « Non meublé »…232233        if re.search(r"garage|stationnement|local", housing_type, re.I):234            return None235        if not unit_type and re.search(r"chambre", housing_type, re.I):236            unit_type = "Chambre"237238        amenities = []239        if housing_type:240            amenities.append(housing_type)241        if atout:242            amenities.append(atout)243244        # ville réelle : Sherbrooke par défaut (parc local) ; East Angus245        # lorsque l'adresse du titre le précise. Lennoxville = secteur.246        city = "East Angus" if re.search(r"east[\s-]angus", title, re.I) else "Sherbrooke"247        if strip_accents(sector.lower()).startswith("arrondissement"):248            sector = ""249250        images = []251        for img in card.select("img.first-image[src], .image-animation-trigger img[src]"):252            src = img["src"]253            if (src.startswith("http") and not _PLACEHOLDER_RE.search(src)254                    and _visible(img) and src not in images):255                images.append(src)256257        return Listing(258            source=self.source_id,259            external_id=slug,260            url=f"{BASE}/logements-a-louer/{slug}",261            title=title or slug.replace("-", " "),262            address=title,263            sector=sector,264            city=city,265            unit_type=unit_type,266            price=parse_price(price_label),267            price_label=price_label,268            availability=availability,269            furnished=_furnished_value(atout),270            amenities=amenities,271            images=images[:5],272        )273274    # -- fiche détail ---------------------------------------------------------------275    def _fetch_detail(self, url: str) -> dict:276        """Blocs .term-block-1 (paires libellé/valeur), description, galerie."""277        html = self.get(url).text278        soup = BeautifulSoup(html, "html.parser")279        out: dict = {}280281        pairs: dict[str, str] = {}282        for blk in soup.select(".term-block-1"):283            lab_el = blk.select_one(".content-title-1")284            if not lab_el:285                continue286            lab = strip_accents(lab_el.get_text(" ", strip=True).lower())287            vals = [" ".join(v.get_text(" ", strip=True).split())288                    for v in blk.select(".terms-text-2") if _visible(v)]289            vals = [v for v in vals if v]290            if lab and vals and lab not in pairs:291                pairs[lab] = vals[0]292        out["pairs"] = pairs293294        rich = next((r for r in soup.select(".w-richtext")295                     if r.find_parent(class_="appartement-item") is None), None)296        if rich:297            txt = rich.get_text("\n", strip=True)298            out["description"] = re.sub(r"[ \t]+", " ", txt).strip()[:1500]299300        # galerie de la fiche : lightbox Webflow (scripts JSON w-json) — les301        # scripts situés dans la section « Poursuivre votre recherche »302        # (.appartement-item = autres annonces) sont exclus303        images: list[str] = []304        for sc in soup.select("script.w-json"):305            if sc.find_parent(class_="appartement-item") is not None:306                continue307            try:308                data = json.loads(sc.string or "")309            except (ValueError, TypeError):310                continue311            for item in (data.get("items") or []):312                src = item.get("url") or ""313                if (src.startswith("http") and not _PLACEHOLDER_RE.search(src)314                        and src not in images):315                    images.append(src)316        out["images"] = images[:30]317        return out318319    def _apply_detail(self, lst: Listing, d: dict) -> None:320        if not d:321            return322        if d.get("description"):323            lst.description = d["description"]324        if d.get("images"):325            lst.images = d["images"]326        pairs = d.get("pairs") or {}327328        extra: list[str] = []329        for lab, val in pairs.items():330            if lab.startswith("etage"):331                extra.append(f"Étage : {val}")332            elif lab.startswith("typologie"):333                extra.append(f"Typologie : {val}")334            elif lab.startswith("stationnement"):335                extra.append(val)336                if re.search(r"inclus|disponible", val, re.I):337                    lst.details["parking"] = {"available": True}338            elif lab.startswith("entree"):339                extra.append(val)340            elif lab.startswith("salle de bain"):341                extra.append(f"{val} salle(s) de bain")342            elif lab.startswith("animaux"):343                extra.append(f"Animaux : {val}")344                pets = _pets_value(val)345                if pets:346                    lst.pets = pets347            elif lab.startswith("ameublement"):348                furn = _furnished_value(val)349                if furn is not None:350                    lst.furnished = furn351            elif lab.startswith("disponibilite") and not lst.availability:352                lst.availability = val353        if extra:354            lst.amenities = list(dict.fromkeys(lst.amenities + extra))355
Files main
Menu

Theme