SPB Git

Repository Public

inspire_laval.py 9.8 KB 228 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/inspire_laval.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/inspire_laval.py : connecteur Groupe Inspire (groupeinspire.ca) —91#   gestionnaire (siège à Terrebonne) d'immeubles résidentiels à Laval92#   (2525 Havre-des-Îles), Montréal (Randall, Trent, Bois-de-Boulogne,93#   Hurteau, LaSalle…). WordPress custom rendu serveur : la page94#   /espaces_disponibles/ affiche des cartes div.location (nom, secteur95#   Résidentiel/Commercial/Industriel, typologies « 3 ½, 4 ½ et 5 ½ »,96#   « à partir de … $ », points forts). La page détail /locations/<slug>/97#   fournit l'adresse civique complète et les photos (via cache detail()).98#   Seules les cartes RÉSIDENTIELLES sont retenues (commercial/industriel99#   exclus). Granularité TYPOLOGIE par immeuble ; le prix « à partir de »100#   n'est associé qu'à la plus petite typologie (jamais de prix inventé).101# -----------------------------------------------------------------------------102from __future__ import annotations103104import re105106from bs4 import BeautifulSoup107108from ..schema import Listing109from .base import BaseConnector110111BASE = "https://groupeinspire.ca"112LIST_URL = f"{BASE}/espaces_disponibles/"113114TYPES_RE = re.compile(r"([2-6])\s*½")115PRICE_RE = re.compile(r"à partir de\s*([\d  ]{3,9})\s*\$", re.I)116# adresse détail : « 2525 Avenue du Havre des Îles, Laval, QC, Canada »117# ou ordre anglais : « 5555 Trent Avenue, Côte Saint-Luc, QC, Canada »118ADDR_RE = re.compile(119    r"(\d{2,5}(?:-\d{2,5})?\s+"120    r"(?:(?:Avenue|Rue|Boulevard|Chemin|Montée|Place)[^,\n]{2,60}"121    r"|[^,\n]{2,60}?(?:Avenue|Street|Boulevard|Road)))"122    r",\s*([\wÀ-ÿ' .-]{3,40}),\s*(?:QC|Québec)", re.I)123IMG_RE = re.compile(r"https://groupeinspire\.ca/wp-content/uploads/"124                    r"[^\"'\s?]+\.(?:jpe?g|png|webp)", re.I)125126127class InspireLavalConnector(BaseConnector):128    source_id = "inspire_laval"129    request_delay = 0.8130131    def fetch(self) -> list[Listing]:132        listings: list[Listing] = []133        try:134            html = self.get(LIST_URL).text135        except Exception:136            return listings137        soup = BeautifulSoup(html, "html.parser")138        for card in soup.select("div.location"):139            cats = [p.get_text(strip=True)140                    for p in card.select(".infos-cats p")]141            if "Résidentiel" not in cats:142                continue                       # industriel/commercial exclus143            link = card.select_one('a[href*="/locations/"]')144            name_el = card.select_one("h4")145            if link is None or name_el is None:146                continue147            url = link.get("href") or LIST_URL148            slug = url.rstrip("/").rsplit("/", 1)[-1]149            name = name_el.get_text(" ", strip=True)150151            specs = [p.get_text(" ", strip=True)152                     for p in card.select(".infos-specs p")]153            types_line = next((s for s in specs if TYPES_RE.search(s)), "")154            types = [f"{n}½" for n in TYPES_RE.findall(types_line)]155            price_label = next((s for s in specs if PRICE_RE.search(s)), "")156            price = None157            pm = PRICE_RE.search(price_label)158            if pm:159                try:160                    price = float(re.sub(r"[  ]", "", pm.group(1)))161                except ValueError:162                    pass163            highlights = [p.get_text(" ", strip=True)164                          for p in card.select(".infos-specs p.highlight")]165            highlights = [h for h in highlights166                          if not h.lower().startswith("parler avec")]167168            detail = self.detail(slug, f"{types_line}|{price_label}",169                                 lambda u=url: self._detail(u))170            address = detail.get("address", "")171            city = detail.get("city", "")172            images = detail.get("images") or []173            description = detail.get("description", "")174            if not city:                       # repli : ville dans le nom175                cm = re.search(r",\s*([\wÀ-ÿ' -]+)$", name)176                city = (cm.group(1).strip() if cm else "")177                city = {"Montreal": "Montréal", "Lasalle": "Montréal"}.get(city, city)178179            # une annonce par typologie ; « à partir de » = plus petite typologie180            for i, ut in enumerate(types or [""]):181                first = (i == 0)182                listings.append(Listing(183                    source=self.source_id,184                    external_id=f"{slug}-{ut.replace('½', '.5') or 'res'}",185                    url=url,186                    title=f"{name} — {ut}" if ut else name,187                    address=address,188                    city=city,189                    unit_type=ut,190                    price=price if first else None,191                    price_label=(price_label if first else ""),192                    availability="Disponible",193                    description=description[:2000],194                    amenities=list(highlights),195                    details=({"price_from": True, "building": name}196                             if first and price else {"building": name}),197                    images=images,198                ))199        return listings200201    # -- page détail /locations/<slug>/ : adresse, photos, descriptif ----------202    def _detail(self, url: str) -> dict:203        payload: dict = {}204        try:205            html = self.get(url).text206        except Exception:207            return payload208        soup = BeautifulSoup(html, "html.parser")209        # adresse : bloc infos de la fiche seulement (le pied de page et les210        # carrousels « autres propriétés » contiennent d'autres adresses)211        scope = (soup.select_one(".top-content") or soup.select_one(".infos")212                 or soup)213        text = scope.get_text("\n", strip=True)214        m = ADDR_RE.search(text)215        if m:216            payload["address"] = m.group(1).strip()217            payload["city"] = m.group(2).strip()218        imgs = [u for u in dict.fromkeys(IMG_RE.findall(html))219                if not re.search(r"logo|icon|-\d+x\d+\.", u, re.I)]220        payload["images"] = imgs[:15]221        # premier paragraphe descriptif substantiel222        for p in soup.select(".content-locations p, .top-content p"):223            t = p.get_text(" ", strip=True)224            if len(t) > 80:225                payload["description"] = t226                break227        return payload228
Files main
Menu

Theme