SPB Git

Repository Public

brochu.py 11.8 KB 288 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/brochu.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0613# Last Modified    : 2026-08-0814#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/brochu.py : connecteur Groupe Immobilier Brochu91#   (groupeimmobilierbrochu.com — Lévis : St-Romuald, Charny, St-Nicolas,92#    centre-ville + Québec : Les Saules). Une annonce par projet/immeuble93#   (pas d'unités individuelles listées sur le site).94# -----------------------------------------------------------------------------95from __future__ import annotations9697import hashlib98import re99100from bs4 import BeautifulSoup101102from ..schema import Listing, infer_city, normalize_unit_type, parse_price103from .base import BaseConnector104105BASE = "https://groupeimmobilierbrochu.com"106LIST_URL = f"{BASE}/projets/"107108# Hors agglomération Québec/Lévis109EXCLUDED_SECTORS = {"saint-lambert-de-lauzon", "st-lambert-de-lauzon"}110111ADDR_RE = re.compile(112    r"\d{1,5},?\s+(?:rue|avenue|av\.|boulevard|boul\.?|chemin|route|rang|"113    r"place|mont[ée]e)\s+[^,<>]{2,50},?\s*(?:L[ée]vis|Qu[ée]bec)"114    r"(?:\s*\(Qu[ée]bec\))?(?:\s*,?\s*[A-Z]\d[A-Z]\s?\d[A-Z]\d)?", re.I)115IMG_RE = re.compile(r"https://groupeimmobilierbrochu\.com/wp-content/uploads/"116                    r'[^"\s\\)]+\.(?:jpe?g|png|webp|avif)', re.I)117PHONE_RE = re.compile(r"\b(\d{3})[\s.\-](\d{3})[\s.\-](\d{4})\b")118119120def _decode_cfemail(hexstr: str) -> str:121    """Décode un courriel protégé Cloudflare (attribut data-cfemail)."""122    try:123        raw = bytes.fromhex(hexstr)124        key = raw[0]125        return bytes(b ^ key for b in raw[1:]).decode("utf-8")126    except Exception:127        return ""128129130class BrochuConnector(BaseConnector):131    source_id = "brochu"132    request_delay = 0.6133    max_projects = 20        # garde-fou de crawl134135    def fetch(self) -> list[Listing]:136        listings: list[Listing] = []137        try:138            html = self.get(LIST_URL).text139        except Exception:140            return listings141        soup = BeautifulSoup(html, "html.parser")142143        seen: set[str] = set()144        for card in soup.select("div.project"):145            if len(seen) >= self.max_projects:146                break147            try:148                a = card.select_one('a[href*="/projets/"]')149                if not a:150                    continue151                url = a.get("href", "").split("?")[0]152                slug = url.rstrip("/").split("/")[-1]153                if not slug or slug in seen:154                    continue155                seen.add(slug)156157                label_el = card.select_one(".uk-label")158                label = label_el.get_text(" ", strip=True) if label_el else ""159                meta_el = card.select_one(".el-meta")160                sector = meta_el.get_text(" ", strip=True) if meta_el else ""161                title_el = card.select_one(".el-title")162                name = title_el.get_text(" ", strip=True) if title_el else slug163                bold_el = card.select_one(".uk-text-bold")164                bold = (re.sub(r"\s+", " ", bold_el.get_text(" ", strip=True))165                        if bold_el else "")166                ps = [p.get_text(" ", strip=True) for p in card.select("p")167                      if p.get_text(strip=True)]168169                # Projets complets ou hors Québec/Lévis : exclure170                full_text = f"{label} {' '.join(ps)}"171                if re.search(r"\bComplet\b", full_text, re.I) and \172                        not re.search(r"disponible|libre", full_text, re.I):173                    continue174                key = sector.lower().replace(" ", "-").replace("--", "-")175                if key in EXCLUDED_SECTORS or "lauzon" in key:176                    continue177178                availability = label or (ps[0] if ps else "")179                price_label = bold if "$" in bold else ""180                unit_type = normalize_unit_type(bold)181                # ne garder qu'un vrai type d'unité (ex. "4½"), pas le texte brut182                if not re.match(r"^\d½$|^Studio$|^Loft$|^Maison$", unit_type):183                    unit_type = ""184                city = infer_city(sector,185                                  default="Québec" if "saules" in key else "Québec")186187                # Page projet : adresse, dispo, description, commodités,188                # contact, photos — via le cache BD des pages détail189                # (revisitée seulement si la carte liste a changé)190                card_key = hashlib.sha1(191                    f"{label}|{sector}|{name}|{bold}|{'|'.join(ps)}"192                    .encode("utf-8")).hexdigest()193                d = self.detail(slug, card_key,194                                lambda url=url: self._fetch_detail(url))195196                if d.get("availability"):197                    availability = d["availability"]198199                details: dict = {}200                contact = {k: d[k] for k in ("phone", "email") if d.get(k)}201                if contact:202                    details["contact"] = contact203204                listings.append(Listing(205                    source=self.source_id,206                    external_id=slug,207                    url=url,208                    title=name,209                    address=d.get("address", ""),210                    sector=sector,211                    city=city,212                    unit_type=unit_type,213                    price=parse_price(price_label),214                    price_label=price_label,215                    availability=availability,216                    description=d.get("description") or bold,217                    amenities=d.get("amenities") or [],218                    details=details,219                    images=d.get("images") or [],220                ))221            except Exception:222                continue223224        return listings225226    def _fetch_detail(self, url: str) -> dict:227        """Extrait les champs riches d'une page projet (thème UIkit).228229        Adresse (lien Google Maps), disponibilité (encadré Statut),230        description + commodités (colonne principale), contact (téléphone231        affiché + courriel protégé Cloudflare décodé), photos.232        """233        out: dict = {}234        try:235            detail = self.get(url).text236        except Exception:237            return out238        dsoup = BeautifulSoup(detail, "html.parser")239240        # adresse : lien Google Maps du projet (hors pied de page, qui porte241        # l'adresse du bureau du Groupe Brochu), sinon regex globale242        for maps in dsoup.select('a[href*="maps"]'):243            if maps.find_parent("footer"):244                continue245            addr = re.sub(r"\s+", " ", maps.get_text(" ", strip=True)).strip()246            if re.search(r"\d", addr):247                out["address"] = addr248                break249        if not out.get("address"):250            dtext = re.sub(r"\s+", " ", dsoup.get_text(" ", strip=True))251            m = ADDR_RE.search(dtext)252            if m:253                out["address"] = m.group(0).strip().rstrip(",")254255        # disponibilité : encadré « Statut » (uk-alert-primary)256        alert = dsoup.select_one("div.uk-alert-primary p")257        if alert:258            out["availability"] = alert.get_text(" ", strip=True)259260        # colonne principale : description (h3 + p) et commodités (li)261        main = dsoup.select_one('div[class*="uk-width-3-5"]')262        if main:263            paras = [p.get_text(" ", strip=True) for p in main.find_all("p")264                     if p.get_text(strip=True)]265            desc = " ".join(paras)266            out["description"] = re.sub(r"\s+", " ", desc).strip()[:900]267            out["amenities"] = [li.get_text(" ", strip=True)268                                for li in main.select("li")269                                if li.get_text(strip=True)][:25]270271        # contact : téléphone affiché dans l'encadré Statut + courriel272        # protégé Cloudflare (data-cfemail, décodable)273        panel = dsoup.select_one("div.uk-panel.uk-background-muted")274        m = PHONE_RE.search(panel.get_text(" ", strip=True) if panel else "")275        if m:276            out["phone"] = f"{m.group(1)}-{m.group(2)}-{m.group(3)}"277        cf = (panel.select_one("[data-cfemail]") if panel else None) or \278            dsoup.select_one("[data-cfemail]")279        if cf:280            email = _decode_cfemail(cf.get("data-cfemail", ""))281            if email:282                out["email"] = email283284        out["images"] = [u for u in dict.fromkeys(IMG_RE.findall(detail))285                         if not re.search(r"logo|icon|favicon|cropped-|"286                                          r"-\d{2,3}x\d{2,3}\.", u, re.I)][:25]287        return out288
Files main
Menu

Theme