SPB Git

Repository Public

deschenes_pepin.py 11.1 KB 274 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/deschenes_pepin.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/deschenes_pepin.py : connecteur Groupe Deschênes Pépin91#   (groupedeschenespepin.com — Montérégie). Promoteur-gestionnaire : projets92#   locatifs « Le Blüm » à Longueuil et Sainte-Julie (50 ans et plus).93#   WordPress/Elementor rendu serveur : la page /louer/ liste les projets,94#   chaque fiche /projet/<slug>/ donne les types d'unités (« 3 ½, 4 ½ et95#   5 ½ »), l'adresse du bureau d'information, la description et la galerie.96#   Granularité : une annonce par projet × typologie (pas d'unités ni de prix97#   publiés sur le site).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/citiluxx/cromwell, hébergeur identique).102# -----------------------------------------------------------------------------103from __future__ import annotations104105import os106import re107import time108from urllib.parse import quote109110from bs4 import BeautifulSoup111112from ..schema import Listing, normalize_unit_type113from .base import BaseConnector114115BASE = "https://groupedeschenespepin.com"116LIST_URL = f"{BASE}/louer/"117118PROJECT_LINK_RE = re.compile(r"https://groupedeschenespepin\.com/projet/([\w\-]+)/?")119UNIT_TOKEN_RE = re.compile(r"\b(\d)\s*(?:½|1/2)")120IMG_RE = re.compile(121    r"https://groupedeschenespepin\.com/wp-content/uploads/"122    r'[^"\s\\)]+\.(?:jpe?g|png|webp|avif)', re.I)123PHONE_RE = re.compile(r"\b(\d{3})[\s.\-](\d{3})[\s.\-](\d{4})\b")124EMAIL_RE = re.compile(r"[\w.\-]+@[\w.\-]+\.\w{2,}")125# adresse civique « 1825 rue du Caribou, Longueuil, Québec J4N 0C9 »126ADDR_RE = re.compile(127    r"\d{1,5}[,]?\s+(?:rue|avenue|av\.|boulevard|boul\.?|chemin|ch\.|route|"128    r"mont[ée]e|place)\s+[^,<>]{2,60},?\s*(?:Longueuil|Sainte-Julie|Ste-Julie)"129    r"[^<>]{0,40}?(?:[A-Z]\d[A-Z]\s?\d[A-Z]\d)?", re.I)130131# page interstitielle sgcaptcha SiteGround (meta refresh vers /.well-known/…)132_SG_MARKER = "/.well-known/sgcaptcha/"133134135def _sg_challenge(resp) -> bool:136    """True si la réponse est le challenge anti-bot SiteGround (202 + JS)."""137    if "challenge" in str(resp.headers.get("sg-captcha", "")).lower():138        return True139    return _SG_MARKER in (resp.text or "")[:600]140141142def _city_of(slug: str, text: str) -> str:143    key = f"{slug} {text}".lower()144    if "sainte-julie" in key or "ste-julie" in key:145        return "Sainte-Julie"146    return "Longueuil"147148149class DeschenesPepinConnector(BaseConnector):150    source_id = "deschenes_pepin"151    request_delay = 0.8152    max_projects = 12          # garde-fou de crawl153154    def _enable_residential_proxy(self) -> bool:155        """Route toute la session via Oxylabs résidentiel CA (session collante)."""156        endpoint = os.environ.get("OXYLABS_PROXY")157        user = os.environ.get("OXYLABS_PROXY_USER")158        pwd = os.environ.get("OXYLABS_PROXY_PASS")159        if not (endpoint and user and pwd):160            return False161        puser = f"{user}-cc-CA-sessid-deschenes{int(time.time())}-sesstime-10"162        proxy = f"http://{quote(puser, safe='')}:{quote(pwd, safe='')}@{endpoint}"163        self.session.proxies = {"http": proxy, "https": proxy}164        self.session.verify = False  # CA MITM du proxy Oxylabs (cf. _resilient)165        return True166167    def _get_html(self, url: str) -> str:168        """GET avec contournement du challenge sgcaptcha (proxy résidentiel)."""169        resp = self.get(url)170        if not _sg_challenge(resp):171            return resp.text172        if not self.session.proxies and self._enable_residential_proxy():173            resp = self.get(url)174            if not _sg_challenge(resp):175                return resp.text176        raise RuntimeError(f"challenge sgcaptcha non contourné — {url}")177178    def fetch(self) -> list[Listing]:179        listings: list[Listing] = []180        # la page de liste échoue franchement (fini le « 0 trouvé ok »181        # silencieux du challenge sgcaptcha — ingest journalise ok=0)182        html = self._get_html(LIST_URL)183184        # Slugs des fiches projet référencées depuis la section « Louer »185        slugs = list(dict.fromkeys(PROJECT_LINK_RE.findall(html)))186        for slug in slugs[: self.max_projects]:187            try:188                listings.extend(self._fetch_project(slug))189            except Exception:190                continue191        return listings192193    def _fetch_project(self, slug: str) -> list[Listing]:194        url = f"{BASE}/projet/{slug}/"195        html = self._get_html(url)196        soup = BeautifulSoup(html, "html.parser")197198        h1 = soup.find("h1")199        name = h1.get_text(" ", strip=True) if h1 else slug.replace("-", " ").title()200        text = re.sub(r"\s+", " ", soup.get_text(" ", strip=True))201202        # à vendre/maisons de ville : on ne garde que les projets locatifs203        # (la page /louer/ ne liste que ceux-là, ceinture et bretelles)204        if re.search(r"\bà vendre\b", name, re.I):205            return []206207        city = _city_of(slug, name)208209        # « Types d'unités 3 ½, 4 ½ et 5 ½ » (bloc d'entête de la fiche)210        m = re.search(r"Types?\s+d'unit[ée]s?\s*([\d\s½,/et]+)", text, re.I)211        unit_zone = m.group(1) if m else text[:2000]212        unit_types = list(dict.fromkeys(213            normalize_unit_type(f"{n}½") for n in UNIT_TOKEN_RE.findall(unit_zone)))214        if not unit_types:215            unit_types = [""]216217        # adresse du bureau d'information (l'immeuble lui-même)218        address = ""219        m = ADDR_RE.search(text)220        if m:221            address = m.group(0).strip().rstrip(",")222223        # description : paragraphe de présentation du projet224        description = ""225        for p in soup.find_all("p"):226            pt = p.get_text(" ", strip=True)227            if len(pt) > 120 and not pt.lower().startswith(("pour offrir", "je reconnais")):228                description = pt[:900]229                break230231        contact: dict = {}232        m = PHONE_RE.search(text)233        if m:234            contact["phone"] = f"{m.group(1)}-{m.group(2)}-{m.group(3)}"235        m = EMAIL_RE.search(text)236        if m:237            contact["email"] = m.group(0).lower()238239        images = [u for u in dict.fromkeys(IMG_RE.findall(html))240                  if not re.search(r"logo|icon|favicon|cropped-|plan|"241                                   r"-\d{2,3}x\d{2,3}\.", u, re.I)][:20]242243        amenities = []244        if re.search(r"50 ans et plus", text, re.I):245            amenities.append("Pour les 50 ans et plus")246        for kw, label in [247            (r"salle d'entra[îi]nement", "Salle d'entraînement"),248            (r"terrasse sur le toit", "Terrasse sur le toit"),249            (r"piscine", "Piscine"),250            (r"stationnement int[ée]rieur", "Stationnement intérieur"),251            (r"ascenseur", "Ascenseur"),252            (r"tout inclus", "Formule tout inclus"),253        ]:254            if re.search(kw, text, re.I):255                amenities.append(label)256257        out: list[Listing] = []258        for ut in unit_types:259            ext = f"{slug}-{ut.replace('½', '.5')}" if ut else slug260            out.append(Listing(261                source=self.source_id,262                external_id=ext,263                url=url,264                title=f"{name} — {ut}" if ut else name,265                address=address,266                city=city,267                unit_type=ut,268                description=description,269                amenities=list(dict.fromkeys(amenities)),270                details={"contact": dict(contact)} if contact else {},271                images=images,272            ))273        return out274
Files main
Menu

Theme