SPB Git

Repository Public

ledomaine.py 8.6 KB 220 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/ledomaine.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/ledomaine.py : connecteur Les Habitations Le Domaine91#   (ledomaine.ca — grand ensemble locatif du quartier Mercier,92#    arrondissement Mercier–Hochelaga-Maisonneuve, Montréal).93#   Site WordPress rendu serveur : une page par typologie94#   (/appartement/appartement-3-et-demi/, etc.) avec prix « à partir de »,95#   description, galerie photos et plan. Une annonce par typologie.96#   Les alias (ex. /appartement-2/) sont dédupliqués via <link rel=canonical>.97# -----------------------------------------------------------------------------98from __future__ import annotations99100import re101102from bs4 import BeautifulSoup103104from ..schema import Listing, normalize_unit_type, parse_price105from .base import BaseConnector106107BASE = "https://www.ledomaine.ca"108109ADDRESS = "2990, Avenue de Granby, Montréal"110SECTOR = "Mercier"111CITY = "Montréal"112113_APT_LINK_RE = re.compile(r"https?://www\.ledomaine\.ca/appartement/([a-z0-9-]+)/?")114_IMG_HREF_RE = re.compile(115    r'href="(https://www\.ledomaine\.ca/wp-content/uploads/[^"]+\.(?:jpg|jpeg|png|webp))"',116    re.I)117_PRICE_RE = re.compile(r"[àa] partir de\s*([\d\s ]+)\s*\$", re.I)118119120class LeDomaineConnector(BaseConnector):121    source_id = "ledomaine"122    request_delay = 0.6123    max_pages = 12               # garde-fou de crawl124125    def fetch(self) -> list[Listing]:126        listings: dict[str, Listing] = {}127        try:128            home = self.get(BASE + "/").text129        except Exception:130            return []131132        slugs = list(dict.fromkeys(_APT_LINK_RE.findall(home)))133        for slug in slugs[: self.max_pages]:134            try:135                lst = self._parse_page(slug)136            except Exception:137                continue138            if lst and lst.external_id not in listings:139                listings[lst.external_id] = lst140        return list(listings.values())141142    def _parse_page(self, slug: str) -> Listing | None:143        url = f"{BASE}/appartement/{slug}/"144        html = self.get(url).text145        soup = BeautifulSoup(html, "html.parser")146147        # Déduplication des alias (/appartement-2/ -> /appartement-3-et-demi/)148        canon = soup.find("link", rel="canonical")149        if canon and canon.get("href"):150            m = _APT_LINK_RE.search(canon["href"])151            if m:152                slug = m.group(1)153                url = f"{BASE}/appartement/{slug}/"154155        h1 = soup.find("h1")156        title = h1.get_text(" ", strip=True) if h1 else slug.replace("-", " ")157158        # « Appartement 4 et demi sous-sol » -> 4½ (mention conservée au titre)159        tm = re.search(r"(\d)\s*et\s*demi", title, re.I)160        unit_type = f"{tm.group(1)}½" if tm else normalize_unit_type(title)161162        # Prix « à partir de NNN $ par mois » (meta description ou corps)163        price = None164        price_label = ""165        meta = soup.find("meta", attrs={"name": "description"})166        sources = [meta.get("content", "") if meta else "",167                   soup.get_text(" ", strip=True)]168        for txt in sources:169            m = _PRICE_RE.search(txt or "")170            if m:171                amount = re.sub(r"[\s ]", "", m.group(1))172                price_label = f"À partir de {amount} $/mois"173                price = parse_price(f"{amount}$")174                break175176        # Description : bloc .text-wrapper sous le h2 « Description de177        # l'appartement » (contient inclusions, balcon, politique animaux…)178        description = ""179        for h2 in soup.find_all("h2"):180            if "description" in h2.get_text(" ", strip=True).lower():181                wrapper = h2.find_parent(class_="text-wrapper") or h2.parent182                parts = []183                for p in wrapper.find_all("p"):184                    t = " ".join(p.get_text(" ", strip=True).split())185                    if t and not t.lower().startswith("consulter"):186                        parts.append(t)187                description = " ".join(parts).strip()[:600]188                break189        if not description:   # repli : ancien découpage textuel190            body_txt = soup.get_text("|", strip=True)191            dm = re.search(192                r"Description\|de l'appartement\|(.{20,900}?)\|Consulter",193                body_txt, re.S)194            if dm:195                description = re.sub(r"\s*\|\s*", " ", dm.group(1))196                description = re.sub(r"\s+", " ", description).strip()[:600]197198        # Toutes les images (galerie + plan) de la page199        images = [u for u in dict.fromkeys(_IMG_HREF_RE.findall(html))200                  if not re.search(r"logo|icon|favicon", u, re.I)]201        if not images:202            return None203204        return Listing(205            source=self.source_id,206            external_id=slug,207            url=url,208            title=f"{title} — Les Habitations Le Domaine",209            address=ADDRESS,210            sector=SECTOR,211            city=CITY,212            unit_type=unit_type,213            price=price,214            price_label=price_label,215            availability="",216            description=description,217            amenities=[],218            images=images,219        )220
Files main
Menu

Theme