Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/logispro.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/logispro.py : connecteur LogisPro Rimouski91# (logisprorimouski.com — Rimouski, parc de 110 logements, 30+ ans). WordPress92# + Elementor + WP Rocket, tout rendu serveur. La page /nos-logements/93# (« Logements disponibles ») liste les unités en location : cartes Elementor94# (adresse, type, photo, bouton « Voir la fiche » vers une page WP par95# unité). La fiche unité /<slug>/ fait foi : h1 = type (« 4 1/2 pièces »),96# h4 = adresse, widget statut (« Disponible » / « Non disponible » -> exclu),97# widget prix nu (« 850.00 », parfois « 600.00$ 655.00$ »), description en98# listes (inclusions, AUCUN ANIMAL, « Disponible Juillet 2026 ») + section99# « À proximité », galerie complète. Fiches via cache BD. Quand aucun100# logement n'est libre la page n'a plus de cartes -> [] (marché plein =101# normal). robots.txt Yoast ouvert, sitemap XML.102# -----------------------------------------------------------------------------103from __future__ import annotations104105import re106107from bs4 import BeautifulSoup108109from ..schema import Listing, normalize_unit_type, parse_price110from .base import BaseConnector111112BASE = "https://logisprorimouski.com"113LIST_URL = f"{BASE}/nos-logements/"114115# widget prix : nombres nus ou avec « $ » (« 850.00 », « 600.00$ 655.00$ »)116_PRICE_WIDGET_RE = re.compile(r"^[\d\s.,$]{3,30}$")117_BARE_PRICE_RE = re.compile(r"^\d{3,4}(?:\.\d{2})?$")118# date plus précise dans la description (« Disponible Juillet 2026 »)119_AVAIL_RE = re.compile(120 r"Disponible\s+(?:d[èe]s\s+)?(?:maintenant|janvier|f[ée]vrier|mars|avril|"121 r"mai|juin|juillet|ao[ûu]t|septembre|octobre|novembre|d[ée]cembre)"122 r"(?:\s+\d{4})?", re.I)123124# pages du site qui ne sont pas des fiches d'unité125_NON_UNITS = {"nos-logements", "nos-proprietes", "nous-joindre",126 "le-william", "le-st-laurent", "le-st-jean"}127128129class LogisproConnector(BaseConnector):130 source_id = "logispro"131 request_delay = 0.6132 max_details = 20 # garde-fou fiches détail (vraies requêtes par sync)133134 def fetch(self) -> list[Listing]:135 html = self.get(LIST_URL).text136 soup = BeautifulSoup(html, "html.parser")137138 self._fetched = 0139 listings: dict[str, Listing] = {}140 # une carte = bouton « Voir la fiche » vers la page de l'unité141 for btn in soup.select("a.elementor-button[href]"):142 try:143 self._parse_card(btn, listings)144 except Exception:145 continue146 return list(listings.values())147148 # -- carte (page « Logements disponibles ») -----------------------------------149 def _parse_card(self, btn, listings: dict[str, Listing]) -> None:150 url = btn["href"]151 m = re.search(r"^https://logisprorimouski\.com/([^/?#]+)/?$", url)152 if not m:153 return154 ext_id = m.group(1)155 if ext_id in _NON_UNITS or ext_id in listings:156 return157158 # photo de la carte (la fiche fournit la galerie complète)159 card = btn160 img = None161 for _ in range(10):162 card = card.parent163 if card is None:164 break165 img = card.select_one('img[src*="/uploads/"]')166 if img is not None:167 break168 images = ([img["src"]] if img and img.get("src", "").startswith("http")169 else [])170171 # la fiche unité fait foi (type h1, adresse h4, statut, prix, photos).172 # Pas de cache BD ici : la liste ne porte ni prix ni statut (aucun173 # signal de fraîcheur pour invalider un cache) et le parc affiché est174 # minuscule (~6 fiches par sync, plafonnées par max_details).175 try:176 payload = self._fetch_detail(url)177 except Exception:178 payload = {}179180 # unité retirée ou marquée « Non disponible » sur sa fiche : on saute181 if re.match(r"^(non\s+disponible|lou[ée])", payload.get("availability", ""),182 re.I):183 return184185 unit_label = payload.get("unit_label", "")186 address = payload.get("address", "")187 lst = Listing(188 source=self.source_id,189 external_id=ext_id,190 url=url,191 title=f"{unit_label} — {address}".strip(" —"),192 address=address,193 city="Rimouski", # tout le parc est à Rimouski194 unit_type=normalize_unit_type(unit_label),195 price=payload.get("price"),196 price_label=payload.get("price_label", ""),197 availability=payload.get("availability", ""),198 description=payload.get("description", ""),199 images=payload.get("images") or images,200 )201 listings[ext_id] = lst202203 # -- fiche unité (/<slug>/) -----------------------------------------------------204 def _fetch_detail(self, url: str) -> dict:205 """Type, adresse, statut, prix (widget nu), description, galerie."""206 if self._fetched >= self.max_details:207 raise RuntimeError("budget de fiches détail atteint")208 self._fetched += 1209 html = self.get(url).text210 soup = BeautifulSoup(html, "html.parser")211 out: dict = {}212213 h1 = soup.select_one("h1.elementor-heading-title")214 if h1:215 out["unit_label"] = h1.get_text(" ", strip=True)216 h4 = soup.select_one("h4.elementor-heading-title")217 if h4:218 out["address"] = h4.get_text(" ", strip=True)219220 # widgets texte Elementor : statut et prix (« 850.00 », « 600.00$ … »)221 for w in soup.select(".elementor-widget-text-editor .elementor-widget-container"):222 t = re.sub(r"\s+", " ", w.get_text(" ", strip=True))223 if "price_label" not in out and _PRICE_WIDGET_RE.match(t) \224 and re.search(r"\d{3}", t):225 out["price_label"] = t226 if "$" in t:227 out["price"] = parse_price(t)228 elif _BARE_PRICE_RE.match(t):229 out["price"] = float(t)230 elif re.match(r"^(non\s+)?disponible\b.{0,40}$|^lou[ée]\b.{0,20}$",231 t, re.I) and "availability" not in out:232 out["availability"] = t233234 # description : sections « Description » et « À proximité » (listes)235 parts: list[str] = []236 for h in soup.select("h5.elementor-heading-title"):237 label = h.get_text(strip=True)238 if not re.match(r"Description|À proximité", label, re.I):239 continue240 section = h.find_parent(class_="e-con")241 if section:242 txt = section.get_text("\n", strip=True)243 parts.append(re.sub(r"[ \t]+", " ", txt))244 if parts:245 desc = "\n".join(parts)246 out["description"] = desc[:1500]247 # date plus précise éventuelle (« Disponible Juillet 2026 »)248 m = _AVAIL_RE.search(desc)249 if m and len(m.group(0)) > len(out.get("availability", "")):250 out["availability"] = re.sub(r"\s+", " ", m.group(0))251252 out["images"] = [253 im["src"] for im in soup.select('img[src*="/uploads/"]')254 if im.get("src", "").startswith("http")255 and not im["src"].endswith(".svg")][:25]256 return out257