SPB Git

Repository Public

mondev.py 13.0 KB 329 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/mondev.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0613# Last Modified    : 2026-09-1314#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/mondev.py : connecteur Mondev (mondev.ca)91#   Grand constructeur-locateur montréalais (Ville-Marie, Sud-Ouest,92#   Griffintown, Plateau, LaSalle, etc.). Site WordPress/Elementor rendu93#   serveur : la page /apartments-and-condos-for-rent/ liste les immeubles94#   (une carte par immeuble, quartier dans l'URL), et chaque fiche immeuble95#   contient un « PLAN SELECTOR » avec, par typologie, « Starting at $X » ou96#   « not available ». Une annonce par (immeuble, typologie) disponible.97#   Prix « à partir de », adresse, description, commodités et galerie photos.98#   2026-09-13 : SiteGround sert son anti-bot sgcaptcha (202 + challenge JS,99#   en-tête sg-captcha) aux IP datacenter — invisible du wrapper résilient100#   (2xx) ; on bascule alors la session sur un proxy résidentiel Oxylabs CA101#   (même pattern que boreal_abitibi/…/mercini, hébergeur identique).102# -----------------------------------------------------------------------------103from __future__ import annotations104105import os106import re107import time108from urllib.parse import quote109110from bs4 import BeautifulSoup111112from ..schema import Listing113from .base import BaseConnector114115BASE = "https://mondev.ca"116LIST_URL = f"{BASE}/apartments-and-condos-for-rent/"117118# page interstitielle sgcaptcha SiteGround (meta refresh vers /.well-known/…)119_SG_MARKER = "/.well-known/sgcaptcha/"120121122def _sg_challenge(resp) -> bool:123    """True si la réponse est le challenge anti-bot SiteGround (202 + JS)."""124    if "challenge" in str(resp.headers.get("sg-captcha", "")).lower():125        return True126    return _SG_MARKER in (resp.text or "")[:600]127128_BUILDING_RE = re.compile(129    r'href="(https://mondev\.ca/apartments-and-condos-for-rent/'130    r'([a-z0-9-]+)/([a-z0-9-]+)/)"')131132# Typologie (site anglophone) -> type normalisé Lou-Ka133_TYPE_MAP = {134    "studio": "Studio",135    "1-bedroom": "3½",136    "2-bedroom": "4½",137    "3-bedroom": "5½",138    "4-bedroom": "6½",139    "penthouse": "Penthouse",140    "loft": "Loft",141    "townhouse": "Maison",142}143144_PLAN_RE = re.compile(145    r"(Studio|\d-bedroom|Penthouse|Loft|Townhouse)\s*[-–]\s*"146    r"(?:Starting at\s*\$\s*([\d,]+)|not\s+available)", re.I)147148# Quartier (slug d'URL) -> nom d'affichage149_ZONES = {150    "ahuntsic-cartierville": "Ahuntsic-Cartierville",151    "cote-des-neiges": "Côte-des-Neiges",152    "downtown": "Centre-ville",153    "griffintown": "Griffintown",154    "lasalle": "LaSalle",155    "little-burgundy": "Petite-Bourgogne",156    "old-montreal": "Vieux-Montréal",157    "park-extension": "Parc-Extension",158    "plateau-mont-royal": "Plateau-Mont-Royal",159    "quartier-des-spectacles": "Quartier des spectacles",160    "rosemont-la-petite-patrie": "Rosemont–La Petite-Patrie",161    "sud-ouest": "Sud-Ouest",162    "ville-marie": "Ville-Marie",163    "ville-saint-laurent": "Saint-Laurent",164    "villeray-saint-michel-parc-extension": "Villeray–Saint-Michel–Parc-Extension",165}166167_ADDR_RE = re.compile(168    r"\d[\w\s.'’&,-]{3,70},\s*(?:Montr[ée]al|(?:Ville )?Saint-Laurent|LaSalle|"169    r"Verdun)\b[^<>\"|]{0,60}", re.I)170# entête d'adresse dédiée : « 605 Rue Fullum, Montreal, QC, Canada H3L 0A9 »171_ADDR_HEAD_RE = re.compile(172    r"^\d{2,5}\b.{5,90}(?:,\s*(?:QC|Qu[ée]bec)\b|,\s*Canada\b)", re.I)173_PHONE_RE = re.compile(r'href="tel:\+?([\d\-() .]{7,20})"')174_GALLERY_RE = re.compile(175    r'href="(https://mondev\.ca/wp-content/uploads/[^"]+?\.(?:jpg|jpeg|png|webp))"'176    r'[^>]*data-elementor-lightbox-slideshow="wl_property_gallery_photos[^"]*"')177178179class MondevConnector(BaseConnector):180    source_id = "mondev"181    request_delay = 0.6182    max_buildings = 45           # garde-fou de crawl183184    def _enable_residential_proxy(self) -> bool:185        """Route toute la session via Oxylabs résidentiel CA (session collante)."""186        endpoint = os.environ.get("OXYLABS_PROXY")187        user = os.environ.get("OXYLABS_PROXY_USER")188        pwd = os.environ.get("OXYLABS_PROXY_PASS")189        if not (endpoint and user and pwd):190            return False191        puser = f"{user}-cc-CA-sessid-mondev{int(time.time())}-sesstime-10"192        proxy = f"http://{quote(puser, safe='')}:{quote(pwd, safe='')}@{endpoint}"193        self.session.proxies = {"http": proxy, "https": proxy}194        self.session.verify = False  # CA MITM du proxy Oxylabs (cf. _resilient)195        return True196197    def _get_html(self, url: str) -> str:198        """GET avec contournement du challenge sgcaptcha (proxy résidentiel)."""199        resp = self.get(url)200        if not _sg_challenge(resp):201            return resp.text202        if not self.session.proxies and self._enable_residential_proxy():203            resp = self.get(url)204            if not _sg_challenge(resp):205                return resp.text206        raise RuntimeError(f"challenge sgcaptcha non contourné — {url}")207208    def fetch(self) -> list[Listing]:209        listings: list[Listing] = []210        # la liste échoue franchement sur challenge (fini le « 0 trouvé ok »211        # silencieux — ingest journalise ok=0)212        index = self._get_html(LIST_URL)213214        buildings: dict[str, tuple[str, str]] = {}215        for url, zone, slug in _BUILDING_RE.findall(index):216            buildings.setdefault(url, (zone, slug))217218        for i, (url, (zone, slug)) in enumerate(buildings.items()):219            if i >= self.max_buildings:220                break221            try:222                listings.extend(self._parse_building(url, zone, slug))223            except Exception:224                continue225        return listings226227    def _parse_building(self, url: str, zone: str, slug: str) -> list[Listing]:228        html = self._get_html(url)229        soup = BeautifulSoup(html, "html.parser")230231        h1 = soup.find("h1")232        name = h1.get_text(" ", strip=True) if h1 else slug.replace("-", " ")233        name = re.sub(r"\s*[-–]\s*(Condo|Apartment)\s+Rentals?\s*$", "", name,234                      flags=re.I).strip()235236        sector = _ZONES.get(zone, zone.replace("-", " ").title())237238        # Adresse civique : entête dédiée (h1-h3 « n° …, QC/Canada »), sinon239        # premier segment de texte ressemblant à une adresse240        address = ""241        for h in soup.select("h1, h2, h3"):242            htxt = h.get_text(" ", strip=True)243            if len(htxt) < 120 and _ADDR_HEAD_RE.match(htxt):244                address = re.sub(r"\s+", " ", htxt).strip().rstrip(",")245                break246        body_txt = soup.get_text("|", strip=True)247        if not address:248            for seg in body_txt.split("|"):249                seg = seg.strip()250                if len(seg) > 120:251                    continue252                am = _ADDR_RE.search(seg)253                if am:254                    address = re.sub(r"\s+", " ",255                                     am.group(0)).strip().rstrip(",")256                    break257258        # Description (meta Yoast)259        description = ""260        meta = soup.find("meta", attrs={"name": "description"})261        if meta and meta.get("content"):262            description = meta["content"].strip()[:600]263264        # Commodités (bloc AMENITIES — icônes structurées)265        amenities = [el.get_text(" ", strip=True)266                     for el in soup.select(".wl_property_amenities li .name")]267        amenities = [a for a in dict.fromkeys(amenities) if a]268269        # Animaux : icône « Pets » dédiée du bloc amenities (structuré)270        pets = "oui" if any(a.strip().lower() in ("pets", "pet friendly")271                            for a in amenities) else None272273        # Contact : lien tel: du bouton d'appel274        details: dict = {}275        pm = _PHONE_RE.search(html)276        if pm:277            digits = re.sub(r"\D", "", pm.group(1))278            if len(digits) == 10:279                details["contact"] = {280                    "phone": f"{digits[0:3]}-{digits[3:6]}-{digits[6:]}"}281282        # Galerie photos (liens lightbox)283        images = list(dict.fromkeys(_GALLERY_RE.findall(html)))[:40]284285        # PLAN SELECTOR : « Studio - Starting at $1,635 » / « not available »286        plan_txt = ""287        marker = soup.find(string=re.compile(r"^\s*PLAN SELECTOR\s*$", re.I))288        if marker:289            widget = marker.find_parent(class_="elementor-widget")290            if widget:291                sib = widget.find_next_sibling(class_="elementor-widget")292                if sib:293                    plan_txt = sib.get_text("\n", strip=True)294        if not plan_txt:295            plan_txt = body_txt.replace("|", "\n")296297        results: list[Listing] = []298        for m in _PLAN_RE.finditer(plan_txt):299            raw_type, raw_price = m.group(1), m.group(2)300            if not raw_price:301                continue                      # typologie non disponible302            type_key = raw_type.lower()303            unit_type = _TYPE_MAP.get(type_key, raw_type)304            try:305                price = float(re.sub(r"[^\d]", "", raw_price))306            except ValueError:307                continue308            if not (100 <= price <= 20000):309                continue310            results.append(Listing(311                source=self.source_id,312                external_id=f"{zone}-{slug}-{type_key}",313                url=url,314                title=f"{name} — {unit_type}",315                address=address,316                sector=sector,317                city="Montréal",318                unit_type=unit_type,319                price=price,320                price_label=f"À partir de {int(price)} $/mois",321                availability="Disponible",322                pets=pets,323                description=description,324                amenities=amenities,325                details=dict(details),326                images=images,327            ))328        return results329
Files main
Menu

Theme