SPB Git

Repository Public

mercille.py 10.1 KB 246 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/mercille.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-2513# Last Modified    : 2026-08-3014#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/mercille.py : connecteur Groupe Mercille (groupemercille.com)91#   Quatre immeubles résidentiels à Longueuil, secteur du métro (Le D'Assigny92#   110 rue de la Barre, Le Neuville Nord/Sud, Le Sérigny). Site custom93#   (Orangium) rendu serveur : la page « Appartements résidentiels » expose94#   une table .table-listings — une ligne par unité disponible : type +95#   disponibilité (« 3.5 1er septembre »), secteur, prix, étage (« 11 de96#   22 »), immeuble (lien vers sa page) et plan PDF. Les lignes du formulaire97#   de contact (repliées sous chaque unité) sont ignorées. La page de chaque98#   immeuble (via cache BD) fournit l'adresse civique et une photo.99#   ⚠️ Le volet espaces commerciaux/bureaux du site n'est pas visité.100# -----------------------------------------------------------------------------101from __future__ import annotations102103import hashlib104import re105import time106107from bs4 import BeautifulSoup108109from ..schema import Listing, normalize_unit_type, parse_price110from .base import BaseConnector111112BASE = "https://groupemercille.com"113LIST_URL = f"{BASE}/appartements-residentiels"114115# type + disponibilité dans la 1re colonne : « 3.5 1er septembre »,116# « 4.5 Disponible maintenant »117TYPE_RE = re.compile(r"^(\d(?:\.5|½)?)\s*(.*)$")118FLOOR_RE = re.compile(r"^(\w+)\s*de\s*(\d+)$")119ADDR_RE = re.compile(120    r"\d{1,5}(?:-\d{1,5})?,?\s+(?:rue|avenue|boulevard|boul\.?|chemin|place)"121    r"\s+[^,|]{2,40},?\s*Longueuil(?:\s*\(Qu[ée]bec\))?"122    r"(?:\s*,?\s*(?:QC\s*)?[A-Z]\d[A-Z]\s?\d[A-Z]\d)?", re.I)123IMG_RE = re.compile(124    r"https://assets\.orangium\.com/api/assets/groupemercille/"125    r"[^\"\s\\']+\.(?:jpe?g|png|webp)", re.I)126127128class MercilleConnector(BaseConnector):129    source_id = "mercille"130    request_delay = 0.6131132    def fetch(self) -> list[Listing]:133        # Un raté transitoire de la page liste (vu 2026-08-29 ~23:20)134        # produisait un faux « 0 trouvé ok » : retry court (backoff 5/10 s),135        # puis erreur franche plutôt qu'un zéro silencieux.136        listings: list[Listing] = []137        table = None138        for attempt in range(3):139            try:140                html = self.get(LIST_URL).text141            except Exception:142                if attempt == 2:143                    raise144            else:145                soup = BeautifulSoup(html, "html.parser")146                table = soup.select_one("table.table-listings")147                if table is not None:148                    break149            if attempt < 2:150                time.sleep(5 * (attempt + 1))151        if table is None:152            raise RuntimeError(153                "table .table-listings introuvable après 3 essais")154155        seen: dict[str, int] = {}156        for tr in table.select("tbody tr"):157            try:158                tds = tr.find_all("td")159                if len(tds) < 5:160                    continue                    # ligne formulaire de contact161                cells = [td.get_text(" ", strip=True) for td in tds]162                m = TYPE_RE.match(cells[0])163                if not m:164                    continue165                unit_type = normalize_unit_type(m.group(1))166                availability = m.group(2).strip()167                sector = cells[1]168                price_label = cells[2]169                floor_label = cells[3]170                building = cells[4]171                if not re.match(r"^\d½$", unit_type) or "$" not in price_label:172                    continue173174                # lien vers la page de l'immeuble + plan PDF de l'unité175                bldg_href = ""176                pdf = ""177                for a in tr.find_all("a", href=True):178                    href = a["href"]179                    if href.lower().endswith(".pdf"):180                        pdf = href181                    elif href.startswith("/"):182                        bldg_href = href183                bslug = bldg_href.strip("/").split("/")[-1] or \184                    re.sub(r"[^a-z0-9]+", "-", building.lower()).strip("-")185186                # identifiant stable : immeuble + type + étage187                floor_key = re.sub(r"[^\w]+", "", floor_label.lower())188                base_id = f"{bslug}-{unit_type.replace('½', '.5')}-{floor_key}"189                seen[base_id] = seen.get(base_id, 0) + 1190                ext_id = base_id if seen[base_id] == 1 else \191                    f"{base_id}-{seen[base_id]}"192193                # page de l'immeuble (cache BD) : adresse civique + photo194                d = {}195                if bldg_href:196                    key = hashlib.sha1(bldg_href.encode()).hexdigest()[:16]197                    d = self.detail(f"bldg:{bslug}", key,198                                    lambda h=bldg_href: self._building(h))199200                details: dict = {}201                mfloor = FLOOR_RE.match(floor_label)202                if mfloor:203                    details["floor_label"] = f"Étage {floor_label}"204                if pdf:205                    details["plan_pdf"] = pdf206207                listings.append(Listing(208                    source=self.source_id,209                    external_id=ext_id,210                    url=f"{BASE}{bldg_href}" if bldg_href else LIST_URL,211                    title=f"{unit_type} — {building}",212                    address=d.get("address", ""),213                    sector=sector,214                    city="Longueuil",215                    unit_type=unit_type,216                    price=parse_price(price_label),217                    price_label=price_label,218                    availability=availability,219                    description=d.get("description", ""),220                    details=details,221                    images=d.get("images") or [],222                ))223            except Exception:224                continue225        return listings226227    def _building(self, href: str) -> dict:228        """Page immeuble : adresse civique (Longueuil), photo, description."""229        out: dict = {}230        try:231            html = self.get(f"{BASE}{href}").text232        except Exception:233            return out234        soup = BeautifulSoup(html, "html.parser")235        text = re.sub(r"\s+", " ", soup.get_text(" ", strip=True))236        m = ADDR_RE.search(text)237        if m:238            out["address"] = m.group(0).strip().rstrip(",")239        # description : premiers paragraphes substantiels de la page240        paras = [p.get_text(" ", strip=True) for p in soup.find_all("p")241                 if len(p.get_text(strip=True)) > 80]242        if paras:243            out["description"] = " ".join(paras)[:700]244        out["images"] = list(dict.fromkeys(IMG_RE.findall(html)))[:10]245        return out246
Files main
Menu

Theme