SPB Git

Repository Public

location_sb.py 10.1 KB 252 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/location_sb.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/location_sb.py : connecteur Location Résidentielle SB91#   (locationresidentielle.com — jumelés, appartements et maisons à louer à92#    Saint-Georges, Beauce). WordPress thème RealHomes rendu serveur : la page93#    /a-louer/ liste des cartes <article class="property-item"> (titre,94#    extrait, vignette, lien /property/<slug>/). Petit inventaire (2-3 fiches95#    actives) ; on écarte les cartes « liste d'attente » et « NON96#    DISPONIBLE ». La page détail (via cache BD) fournit adresse, chambres,97#    salles de bain, prix ($/mois — souvent « communiquez avec nous »),98#    disponibilité, caractéristiques (<li>) et photos.99# -----------------------------------------------------------------------------100from __future__ import annotations101102import hashlib103import re104105from bs4 import BeautifulSoup106107from ..schema import Listing, normalize_unit_type, parse_price108from .base import BaseConnector109110BASE = "https://locationresidentielle.com"111LIST_URL = f"{BASE}/a-louer/"112113CITY = "Saint-Georges"114115SLUG_RE = re.compile(r"/property/([^/?#]+)")116# cartes qui ne sont pas de vraies annonces117SKIP_RE = re.compile(r"liste\s+d.attente|inscription|non\s+disponible", re.I)118ADDR_RE = re.compile(r"(\d{3,6},?\s+\d{1,3}e\s+(?:Rue|Avenue),?\s+"119                     r"(?:Saint|St)-Georges(?:,?\s+G\d[A-Z]\s*\d[A-Z]\d)?)",120                     re.I)121BED_RE = re.compile(r"(\d+)\s*(?:grandes?\s*)?chambres", re.I)122BATH_RE = re.compile(r"(\d+)\s*salles? de bain", re.I)123PRICE_RE = re.compile(r"(\d[\d\s]{2,6})\s*\$\s*/?\s*mois", re.I)124DISPO_RE = re.compile(r"(?:Disponibilit[ée]\s*:\s*([^\n]{2,60})|"125                      r"((?:CESSION DE BAIL\s+)?DISPONIBLE EN [A-ZÉÛ]+))")126TYPE_RE = re.compile(r"\d\s*1/2")127UNIT_TEL_RE = re.compile(r"\b(\d{3})[\s.\-](\d{3})[\s.\-](\d{4})\b")128IMG_RE = re.compile(r'(?:src|href)="(https://locationresidentielle\.com/'129                    r'wp-content/uploads/[^"]+\.(?:jpe?g|png|webp))"', re.I)130IMG_SKIP_RE = re.compile(r"logo|signature|carte|a_louer|"131                         r"jumeles-appartements|-\d{2,3}x\d{2,3}\.", re.I)132133134class LocationSbConnector(BaseConnector):135    source_id = "location_sb"136    request_delay = 0.6137138    def fetch(self) -> list[Listing]:139        listings: list[Listing] = []140        html = self.get(LIST_URL).text141        soup = BeautifulSoup(html, "html.parser")142143        for item in soup.select("article.property-item"):144            try:145                a = item.select_one("h4 a[href]")146                if not a:147                    continue148                title = re.sub(r"[•\s]+", " ", a.get_text(strip=True)).strip()149                if not title or SKIP_RE.search(title):150                    continue151                m = SLUG_RE.search(a["href"])152                if not m:153                    continue154                slug = m.group(1)155                url = f"{BASE}/property/{slug}/"156157                excerpt = ""158                p = item.find("p")159                if p:160                    excerpt = re.sub(161                        r"\s+", " ",162                        p.get_text(" ", strip=True)).replace(163                        "Plus d'informations", "").strip(" …-")164165                key = hashlib.sha1(166                    f"{url}|{title}|{excerpt}".encode()).hexdigest()167                try:168                    d = self.detail(slug, key, lambda u=url: self._detail(u))169                except Exception:170                    d = {}171172                tm = TYPE_RE.search(title)173                unit_type = normalize_unit_type(tm.group(0)) if tm else ""174175                listings.append(Listing(176                    source=self.source_id,177                    external_id=slug,178                    url=url,179                    title=title,180                    address=d.get("address")181                    or f"{title}, Saint-Georges",182                    city=CITY,183                    unit_type=unit_type,184                    bedrooms=d.get("bedrooms"),185                    bathrooms=d.get("bathrooms"),186                    price=d.get("price"),187                    price_label=d.get("price_label", ""),188                    availability=d.get("availability", ""),189                    description=d.get("description") or excerpt,190                    amenities=d.get("amenities") or [],191                    details=d.get("details") or {},192                    images=d.get("images") or [],193                ))194            except Exception:195                continue196        return listings197198    # -- page détail /property/<slug>/ (thème RealHomes) ------------------------199    def _detail(self, url: str) -> dict:200        html = self.get(url).text201        soup = BeautifulSoup(html, "html.parser")202        art = soup.find("article") or soup203        txt = re.sub(r"[ \t]+", " ", art.get_text("\n", strip=True))204        flat = re.sub(r"\s+", " ", txt)205        out: dict = {}206207        m = ADDR_RE.search(flat)208        if m:209            addr = re.sub(r"\s+", " ", m.group(1)).strip()210            if not re.search(r"saint-georges", addr, re.I):211                addr = re.sub(r"St-Georges", "Saint-Georges", addr, flags=re.I)212            out["address"] = addr213        m = BED_RE.search(flat)214        if m:215            out["bedrooms"] = float(m.group(1))216        m = BATH_RE.search(flat)217        if m:218            out["bathrooms"] = float(m.group(1))219        m = PRICE_RE.search(flat)220        if m:221            out["price"] = parse_price(m.group(0))222            out["price_label"] = f"{m.group(1).strip()} $/mois"223        elif re.search(r"Prix\s*:\s*communiquez", flat, re.I):224            out["price_label"] = "Prix : communiquez avec nous"225        m = DISPO_RE.search(txt)226        if m:227            out["availability"] = (m.group(1) or m.group(2) or "") \228                .strip().capitalize()229230        # caractéristiques / inclusions : listes <li> du contenu231        amenities: list[str] = []232        for li in art.find_all("li"):233            t = re.sub(r"\s+", " ", li.get_text(" ", strip=True))234            t = re.sub(r"^[^\w]+|►.*$", "", t).strip()235            if (t and 3 <= len(t) < 80 and "ICI" not in t236                    and not re.search(r"estimez|inscrivez", t, re.I)237                    and t not in amenities):238                amenities.append(t)239        out["amenities"] = amenities[:20]240241        details: dict = {}242        pm = UNIT_TEL_RE.search(flat)243        if pm:244            details["contact"] = {245                "phone": f"{pm.group(1)}-{pm.group(2)}-{pm.group(3)}"}246        if details:247            out["details"] = details248249        out["images"] = [u for u in dict.fromkeys(IMG_RE.findall(html))250                         if not IMG_SKIP_RE.search(u)][:15]251        return out252
Files main
Menu

Theme