Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/gestion_fauvel.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/gestion_fauvel.py : connecteur Gestion Fauvel (gestionfauvel.com)91# WordPress + Elementor + JetEngine. La page /logements-a-louer/ expose une92# grille .jet-listing-grid__item : data-post-id (id stable), data-url,93# en-têtes (disponibilité, prix, titre) et terme JetEngine = ville réelle.94# Fiches détail (cache BD) : adresse civique, description complète (unités95# dispo + inclusions) et galerie photos (carrousel Elementor).96# -----------------------------------------------------------------------------97from __future__ import annotations9899import hashlib100import re101102from bs4 import BeautifulSoup103104from ..schema import Listing, normalize_unit_type, parse_price105from .base import BaseConnector106107BASE = "https://gestionfauvel.com"108LIST_URL = f"{BASE}/logements-a-louer/"109110# adresse civique : « 555, rue des Écoles, app. 105 Drummondville »111_ADDR_RE = re.compile(112 r"^\d+[\s,]+.*\b(rue|boul(?:evard|\.)?|avenue|av\.|chemin|carr[ée]|place|"113 r"c[ôo]te|mont[ée]e|rang)\b", re.I)114_IMG_EXT_RE = re.compile(r"\.(?:jpe?g|png|webp)$", re.I)115_UNIT_RE = re.compile(r"^(?:\d½\+?|Studio|Loft|Maison)$")116117118class GestionFauvelConnector(BaseConnector):119 source_id = "gestion_fauvel"120 request_delay = 0.6121 max_details = 25 # garde-fou fiches détail (vraies requêtes)122123 def fetch(self) -> list[Listing]:124 listings: dict[str, Listing] = {}125 soup = BeautifulSoup(self.get(LIST_URL).text, "html.parser")126 for card in soup.select(".jet-listing-grid__item"):127 try:128 self._parse_card(card, listings)129 except Exception:130 continue131132 # fiches détail (cache BD) : adresse, description, photos133 self._fetched = 0134 for lst in listings.values():135 card_key = hashlib.sha1(136 f"{lst.title}|{lst.price_label}|{lst.availability}"137 .encode("utf-8")).hexdigest()138 try:139 payload = self.detail(lst.external_id, card_key,140 lambda u=lst.url: self._fetch_detail(u))141 except Exception:142 continue143 self._apply_detail(lst, payload)144 return list(listings.values())145146 # -- carte JetEngine ------------------------------------------------------147 def _parse_card(self, card, listings: dict[str, Listing]) -> None:148 ext_id = card.get("data-post-id", "")149 overlay = card.select_one(".jet-engine-listing-overlay-wrap[data-url]")150 url = overlay.get("data-url") if overlay else ""151 if not ext_id or not url or ext_id in listings:152 return153154 heads = [h.get_text(" ", strip=True)155 for h in card.select(".elementor-heading-title")156 if h.get_text(strip=True)]157 if not heads:158 return159 title = re.sub(r"\s+", " ", heads[-1]) # le titre ferme la carte160 price_label = next((h for h in heads[:-1] if "$" in h), "")161 avail_parts = [h for h in heads[:-1] if h != price_label]162 availability = " ".join(avail_parts).strip()163164 # exclusions : immeubles complets, volet commercial165 if re.search(r"complet", availability + " " + title, re.I):166 return167 if re.search(r"commercial|bureau|local|entrep[ôo]t|stationnement",168 title, re.I):169 return170171 terms = card.select_one(".jet-listing-dynamic-terms")172 city = terms.get_text(" ", strip=True) if terms else ""173174 unit_type = normalize_unit_type(title)175 if not _UNIT_RE.fullmatch(unit_type or ""):176 unit_type = "" # titre sans format d'unité (ex. « Condos locatifs »)177178 images = []179 img = card.select_one("img[src]")180 if img and img["src"].startswith("http"):181 images = [img["src"]]182183 listings[str(ext_id)] = Listing(184 source=self.source_id,185 external_id=str(ext_id),186 url=url,187 title=title,188 city=city,189 unit_type=unit_type,190 price=parse_price(price_label),191 price_label=price_label,192 availability=availability,193 images=images,194 )195196 # -- fiche détail (Elementor) ----------------------------------------------197 def _fetch_detail(self, url: str) -> dict:198 """Adresse civique (en-tête h3), description (bloc après le h2199 « Description ») et galerie photos (liens pleine taille du carrousel)."""200 if self._fetched >= self.max_details:201 raise RuntimeError("budget de fiches détail atteint")202 self._fetched += 1203 soup = BeautifulSoup(self.get(url).text, "html.parser")204 out: dict = {}205206 for h3 in soup.select("h3.elementor-heading-title"):207 txt = h3.get_text(" ", strip=True)208 if _ADDR_RE.match(txt):209 out["address"] = txt210 break211212 desc_h2 = next((h for h in soup.select("h2")213 if h.get_text(strip=True).lower() == "description"), None)214 if desc_h2:215 parts: list[str] = []216 for el in desc_h2.find_all_next(["p", "li", "h2"]):217 if el.name == "h2":218 break219 t = re.sub(r"\s+", " ", el.get_text(" ", strip=True))220 if t and t not in parts:221 parts.append(t)222 if parts:223 out["description"] = "\n".join(parts)[:2000]224225 images: list[str] = []226 for a in soup.select(".elementor-widget-image-carousel a[href]"):227 u = a["href"]228 if u.startswith("http") and _IMG_EXT_RE.search(u) and u not in images:229 images.append(u)230 out["images"] = images[:30]231 return out232233 def _apply_detail(self, lst: Listing, d: dict) -> None:234 """Reporte le payload (frais/cache) sur l'annonce."""235 if not d:236 return237 if d.get("address"):238 lst.address = d["address"]239 if d.get("description"):240 lst.description = d["description"]241 if d.get("images"):242 lst.images = list(dict.fromkeys(d["images"] + lst.images))[:30]243