SPB Git

Repository Public

gestion_mj.py 11.7 KB 283 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/gestion_mj.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-2513# 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/gestion_mj.py : connecteur Gestion Immobilière M.J (gestionmj.com)91#   Immeuble du 9155 rue Meilleur, Montréal (Ahuntsic / district Chabanel).92#   WordPress (thème Astra) rendu serveur avec CPT « a-louer » exposé en93#   REST (/wp-json/wp/v2/a-louer) : on énumère les annonces via l'API puis94#   on parse chaque page détail (h2.price, p.address, p.availability,95#   section Détails = commodités, Description, galerie).96#   ⚠️ Les blocs icônes (chambres / pi² / étage) et la date de disponibilité97#   sont des valeurs de gabarit IDENTIQUES sur toutes les pages (« 298#   chambre(s) », « 900 pi² », « 02/03/2025 ») → chambres/typologie dérivées99#   du TITRE (« Studio moderne », « Appartement 2/3 chambres »), icônes100#   reléguées en details. Granularité : une annonce par unité (post CPT).101#   2026-09-13 : SiteGround sert son anti-bot sgcaptcha (202 + challenge JS,102#   en-tête sg-captcha) aux IP datacenter — invisible du wrapper résilient103#   (2xx) ; on bascule alors la session sur un proxy résidentiel Oxylabs CA104#   (même pattern que boreal_abitibi/citiluxx/cromwell/deschenes_pepin/105#   gestion_habitation/gimcote/appartements_rimouski/lbm, hébergeur106#   identique).107# -----------------------------------------------------------------------------108from __future__ import annotations109110import json111import os112import re113import time114from urllib.parse import quote115116from bs4 import BeautifulSoup117118from ..schema import Listing, normalize_unit_type, parse_price119from .base import BaseConnector120121BASE = "https://gestionmj.com"122API_URL = (f"{BASE}/wp-json/wp/v2/a-louer?per_page=100"123           "&_fields=id,slug,link,title,modified")124125# page interstitielle sgcaptcha SiteGround (meta refresh vers /.well-known/…)126_SG_MARKER = "/.well-known/sgcaptcha/"127128129def _sg_challenge(resp) -> bool:130    """True si la réponse est le challenge anti-bot SiteGround (202 + JS)."""131    if "challenge" in str(resp.headers.get("sg-captcha", "")).lower():132        return True133    return _SG_MARKER in (resp.text or "")[:600]134135BED_TITLE_RE = re.compile(r"(\d)\s*chambres?", re.I)136IMG_RE = re.compile(r"https://gestionmj\.com/wp-content/uploads/"137                    r'[^"\s\\)]+\.(?:jpe?g|png|webp)', re.I)138139140class GestionMJConnector(BaseConnector):141    source_id = "gestion_mj"142    request_delay = 0.7143144    def _enable_residential_proxy(self) -> bool:145        """Route toute la session via Oxylabs résidentiel CA (session collante)."""146        endpoint = os.environ.get("OXYLABS_PROXY")147        user = os.environ.get("OXYLABS_PROXY_USER")148        pwd = os.environ.get("OXYLABS_PROXY_PASS")149        if not (endpoint and user and pwd):150            return False151        puser = f"{user}-cc-CA-sessid-gestionmj{int(time.time())}-sesstime-10"152        proxy = f"http://{quote(puser, safe='')}:{quote(pwd, safe='')}@{endpoint}"153        self.session.proxies = {"http": proxy, "https": proxy}154        self.session.verify = False  # CA MITM du proxy Oxylabs155        return True156157    def _get_html(self, url: str) -> str:158        """GET avec contournement du challenge sgcaptcha (proxy résidentiel)."""159        resp = self.get(url)160        if not _sg_challenge(resp):161            return resp.text162        if not self.session.proxies and self._enable_residential_proxy():163            resp = self.get(url)164            if not _sg_challenge(resp):165                return resp.text166        raise RuntimeError(f"challenge sgcaptcha non contourné — {url}")167168    def fetch(self) -> list[Listing]:169        listings: list[Listing] = []170        # échec franc sur challenge/panne (fini le « 0 trouvé ok » silencieux)171        posts = json.loads(self._get_html(API_URL))172        if not isinstance(posts, list):173            raise RuntimeError("réponse wp-json inattendue (pas une liste)")174175        for post in posts:176            try:177                slug = post.get("slug", "")178                url = (post.get("link") or "").split("?")[0]179                if not slug or "/a-louer/" not in url:180                    continue181                title = BeautifulSoup(182                    (post.get("title") or {}).get("rendered", ""),183                    "html.parser").get_text(" ", strip=True) or slug184185                d = self.detail(slug, str(post.get("modified", "")),186                                lambda url=url: self._fetch_detail(url))187188                # typologie/chambres depuis le TITRE (icônes non fiables)189                bedrooms = None190                if re.search(r"\bstudio\b", title, re.I):191                    bedrooms = 0.0192                else:193                    m = BED_TITLE_RE.search(title)194                    if m:195                        bedrooms = float(m.group(1))196                unit_type = normalize_unit_type(197                    "Studio" if bedrooms == 0.0198                    else (f"{int(bedrooms)} chambres" if bedrooms else ""))199200                listings.append(Listing(201                    source=self.source_id,202                    external_id=slug,203                    url=url,204                    title=title,205                    address=d.get("address", ""),206                    city="Montréal",207                    sector="Ahuntsic-Cartierville",208                    unit_type=unit_type,209                    bedrooms=bedrooms,210                    price=d.get("price"),211                    availability=d.get("availability", ""),212                    furnished="Meublé" in (d.get("amenities") or []),213                    description=d.get("description", ""),214                    amenities=d.get("amenities") or [],215                    details=d.get("details") or {},216                    images=d.get("images") or [],217                ))218            except Exception:219                continue220        return listings221222    def _fetch_detail(self, url: str) -> dict:223        out: dict = {}224        # _get_html lève sur challenge : pas de {} vide dans detail_cache225        # (clé figée jamais invalidée)226        html = self._get_html(url)227        soup = BeautifulSoup(html, "html.parser")228229        el = soup.select_one("h2.price")230        if el:231            out["price"] = parse_price(el.get_text(" ", strip=True))232        el = soup.select_one("p.address")233        if el:234            out["address"] = re.sub(r"\s+", " ",235                                    el.get_text(" ", strip=True)).strip()236        el = soup.select_one("p.availability")237        if el:238            out["availability"] = re.sub(239                r"\s+", " ", el.get_text(" ", strip=True)).strip()240241        # section « Détails » : commodités (li)242        h = soup.find(string=re.compile(r"^\s*Détails\s*$"))243        amenities: list[str] = []244        if h:245            sec = h.find_parent(["div", "section"])246            for _ in range(3):247                if sec is None:248                    break249                lis = sec.select("li")250                if lis:251                    amenities = [li.get_text(" ", strip=True)252                                 for li in lis253                                 if 0 < len(li.get_text(strip=True)) <= 60]254                    break255                sec = sec.parent256        out["amenities"] = amenities[:15]257258        # description : paragraphes après le titre « Description »259        h = soup.find(string=re.compile(r"^\s*Description\s*$"))260        if h:261            par = h.find_parent(["div", "section"])262            ps = [p.get_text(" ", strip=True)263                  for p in (par.find_all_next("p", limit=3) if par else [])264                  if len(p.get_text(strip=True)) > 60]265            if ps:266                out["description"] = re.sub(r"\s+", " ",267                                            " ".join(ps[:2]))[:900]268269        # icônes gabarit (non fiables) → details, à titre indicatif270        details: dict = {}271        for sel, key in (("p.icon.square-footage", "gabarit_superficie"),272                         ("p.icon.floor", "gabarit_etage")):273            el = soup.select_one(sel)274            if el:275                details[key] = el.get_text(" ", strip=True)276        out["details"] = details277278        out["images"] = [279            u for u in dict.fromkeys(IMG_RE.findall(html))280            if not re.search(r"logo|icon|favicon|-\d{2,3}x\d{2,3}\.", u, re.I)281        ][:20]282        return out283
Files main
Menu

Theme