Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/connectors/trouve_ton_appart.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-2513# Last Modified : 2026-08-2514#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/trouve_ton_appart.py : connecteur Trouve-Ton-Appart91# (trouve-ton-appart.com — regroupe 3 propriétaires familiaux : Construction92# Léandre Demers, Immeubles Des Rochers, Immeubles Morency). ~229 fiches93# dans Lotbinière (Laurier-Station, St-Flavien, St-Agapit, St-Apollinaire),94# Lévis (St-Nicolas, St-Rédempteur, St-Romuald), Québec, Ste-Marie et95# Trois-Rivières. Page /logements/ rendue serveur (PHP maison « Dix-Onze ») :96# sections <h2>Ville</h2> puis cartes div.loge — pastille img.dispo97# green.png = Disponible / red.png = Non disponible. On n'ingère QUE les98# unités disponibles (pastille verte). Fiche /logements/logement/<id>/<slug>/99# (via cache BD) : description, grandeur + prix, propriétaire gestionnaire100# (nom + téléphone + courriel) et photo principale.101# -----------------------------------------------------------------------------102from __future__ import annotations103104import hashlib105import re106107from bs4 import BeautifulSoup108109from ..schema import Listing, infer_city, normalize_unit_type110from .base import BaseConnector111112BASE = "https://www.trouve-ton-appart.com"113LIST_URL = f"{BASE}/logements/"114115# « 940 $ » (span.plus) puis « / mois 6½ » dans la même rangée116PRICE_RE = re.compile(r"([\d\s]+)\s*\$")117TYPE_RE = re.compile(r"/\s*mois\s*([\d]\s*½|Studio|Loft)", re.I)118LOGEMENT_URL_RE = re.compile(r"/logements/logement/(\d+)/([^/?#]+)")119PHONE_RE = re.compile(r"(\d{3})[\s.\-](\d{3})[\s.\-](\d{4})")120# photos : /app_photos/<id>/pp_<hash>.<ext> (pleine taille, hors /thumbnails/)121PHOTO_RE = re.compile(r"/app_photos/\d+/(?!thumbnails/)[^\"'\s)]+"122 r"\.(?:jpe?g|png|webp)", re.I)123124# villes du site -> ville canonique Lou-Ka (le reste passe par infer_city)125CITY_MAP = {126 "Ste-Marie-de-Beauce": "Sainte-Marie",127 "St-Agapit": "Saint-Agapit",128 "St-Apollinaire": "Saint-Apollinaire",129 "St-Flavien": "Saint-Flavien",130}131132133class TrouveTonAppartConnector(BaseConnector):134 source_id = "trouve_ton_appart"135 request_delay = 0.6136 max_details = 40 # garde-fou fiches détail (vraies requêtes par sync)137138 def fetch(self) -> list[Listing]:139 listings: list[Listing] = []140 html = self.get(LIST_URL).text141 soup = BeautifulSoup(html, "html.parser")142 self._fetched = 0143144 container = soup.select_one("#logements") or soup145 city_label = ""146 for el in container.find_all(["h2", "div"], recursive=True):147 if el.name == "h2":148 city_label = el.get_text(strip=True)149 continue150 if "loge" not in (el.get("class") or []):151 continue152 try:153 lst = self._parse_card(el, city_label)154 if lst is not None:155 listings.append(lst)156 except Exception:157 continue158 return listings159160 # -- carte (div.loge d'une section <h2>Ville</h2>) -------------------------------161 def _parse_card(self, card, city_label: str) -> Listing | None:162 # pastille de disponibilité : on n'ingère que le vert (Disponible)163 badge = card.select_one("img.dispo")164 badge_src = (badge.get("src") or "") if badge else ""165 if "green" not in badge_src:166 return None167168 link = card.select_one('a[href*="/logements/logement/"]')169 if not link:170 return None171 m = LOGEMENT_URL_RE.search(link.get("href") or "")172 if not m:173 return None174 ext_id, slug = m.group(1), m.group(2)175 url = f"{BASE}/logements/logement/{ext_id}/{slug}/"176177 detail_div = card.select_one("div.detail")178 text = re.sub(r"\s+", " ",179 detail_div.get_text(" ", strip=True)) if detail_div else ""180 addr_el = card.select_one("div.detail div.plus")181 street = addr_el.get_text(strip=True) if addr_el else ""182183 # prix : le <span class="plus"> de la rangée prix (« 940 $ »), pour ne184 # pas absorber un numéro civique du genre « route 273 » dans le montant185 price = None186 price_label = ""187 unit_type = ""188 price_el = detail_div.select_one("span.plus") if detail_div else None189 pm = PRICE_RE.search(price_el.get_text(" ", strip=True)) if price_el \190 else None191 if pm:192 try:193 val = float(re.sub(r"\s", "", pm.group(1)))194 if 100 <= val <= 20000:195 price = val196 price_label = f"{int(val)} $ / mois"197 except ValueError:198 pass199 tm = TYPE_RE.search(text)200 if tm:201 unit_type = normalize_unit_type(tm.group(1))202203 city = CITY_MAP.get(city_label) or infer_city(city_label,204 default=city_label)205206 # vignette de la liste (repli si la fiche n'a pas de photo pleine taille)207 images: list[str] = []208 thumb = card.select_one("img.image")209 if thumb and thumb.get("src"):210 src = thumb["src"]211 images.append(src if src.startswith("http") else BASE + src)212213 lst = Listing(214 source=self.source_id,215 external_id=ext_id,216 url=url,217 title=f"{street}, {city_label}" if street else city_label,218 address=f"{street}, {city_label}" if street else "",219 city=city,220 unit_type=unit_type,221 price=price,222 price_label=price_label,223 availability="Disponible",224 images=images,225 )226227 key = hashlib.sha1(f"{street}|{text}|{city_label}|green"228 .encode("utf-8")).hexdigest()229 try:230 d = self.detail(ext_id, key, lambda u=url: self._fetch_detail(u))231 self._apply_detail(lst, d)232 except Exception:233 pass234 return lst235236 # -- fiche détail (/logements/logement/<id>/<slug>/) -----------------------------237 def _fetch_detail(self, url: str) -> dict:238 """Description, grandeur/prix, propriétaire (nom, tél., courriel), photos."""239 if self._fetched >= self.max_details:240 raise RuntimeError("budget de fiches détail atteint")241 self._fetched += 1242 html = self.get(url).text243 soup = BeautifulSoup(html, "html.parser")244 out: dict = {}245246 # description : premier <p> sous <h2>Description</h2>247 for h2 in soup.find_all("h2"):248 if "description" in h2.get_text(strip=True).lower():249 p = h2.find_next("p")250 if p:251 out["description"] = re.sub(252 r"\s+", " ", p.get_text(" ", strip=True)).strip()[:1200]253 break254255 # propriétaire gestionnaire : <h3> sous « Pour location » + tel:/mailto:256 anchor = soup.find("a", attrs={"id": "location"})257 h3 = anchor.find_next("h3") if anchor else soup.find("h3")258 if h3 and h3.get_text(strip=True):259 out["manager"] = h3.get_text(strip=True)260 m = re.search(r'href="mailto:([^"?]+)"', html)261 if m:262 out["email"] = m.group(1).strip().lower()263 m = re.search(r'href="tel:\+?1?(\d{10})"', html)264 if m:265 d10 = m.group(1)266 out["phone"] = f"{d10[:3]}-{d10[3:6]}-{d10[6:]}"267268 # photos pleine taille (/app_photos/<id>/pp_*.ext hors miniatures)269 photos = [u if u.startswith("http") else BASE + u270 for u in dict.fromkeys(PHOTO_RE.findall(html))]271 if photos:272 out["images"] = photos[:20]273 return out274275 def _apply_detail(self, lst: Listing, d: dict) -> None:276 if not d:277 return278 if d.get("description"):279 lst.description = d["description"]280 contact = {k: d[k] for k in ("phone", "email") if d.get(k)}281 if d.get("manager"):282 contact["name"] = d["manager"]283 if contact:284 lst.details["contact"] = contact285 if d.get("images"):286 lst.images = d["images"]287