SPB Git

Repository Public

courtemanche.py 11.3 KB 276 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/courtemanche.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0913# Last Modified    : 2026-08-0914#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/courtemanche.py : connecteur Gestion Immobilière Courtemanche91#   (gestioncourtemanche.ca — Saguenay : Chicoutimi/Chicoutimi-Nord, plusieurs92#   centaines d'unités, leader du Saguenay). WordPress + Beaver Builder +93#   plugin maison « realestate », tout rendu serveur. Liste /location/tous/94#   (taxonomie real-estate-location) : cartes `.real-estate-box` avec type95#   (« 1 1/2 »), adresse, prix (« 700 $ / mois »), inclusions et date « Libre96#   le » ; quand aucun logement n'est libre, la page affiche « Aucun logement97#   disponible… » et le connecteur retourne une liste vide — situation normale98#   sur ce marché (taux d'inoccupation très bas au Saguenay). Fiche détail99#   /immobilier/<slug>/ (via cache BD) : description, caractéristiques100#   (taxonomie real-estate-characteristic), GPS (carte Google du plugin) et101#   secteur (lien « Retour » vers /location/<secteur>/).102#   robots.txt Yoast ouvert, sitemaps real-estate-location/-characteristic.103# -----------------------------------------------------------------------------104from __future__ import annotations105106import hashlib107import re108from urllib.parse import unquote109110from bs4 import BeautifulSoup111112from ..schema import Listing, normalize_unit_type, parse_price, strip_accents113from .base import BaseConnector114115BASE = "https://gestioncourtemanche.ca"116LIST_URL = f"{BASE}/location/tous/"117118_BG_URL_RE = re.compile(r"background-image\s*:\s*url\(([^)]+)\)")119_MAP_LATLNG_RE = re.compile(r"LatLng\((-?\d+\.\d+),\s*(-?\d+\.\d+)\)")120121# libellés des secteurs (taxonomie real-estate-location du site)122_SECTORS = {123    "chicoutimi-centres-commerciaux": "Chicoutimi — Centres commerciaux",124    "chicoutimi-uqac-cegep": "Chicoutimi — UQAC/CÉGEP",125    "chicoutimi-nord": "Chicoutimi-Nord",126}127128129class CourtemancheConnector(BaseConnector):130    source_id = "courtemanche"131    request_delay = 0.6132    max_details = 40     # garde-fou fiches détail (vraies requêtes par sync)133134    def fetch(self) -> list[Listing]:135        html = self.get(LIST_URL).text136        soup = BeautifulSoup(html, "html.parser")137138        self._fetched = 0139        listings: dict[str, Listing] = {}140        # cartes présentes seulement quand des logements sont libres ; sinon la141        # page affiche « Aucun logement disponible dans ce secteur… » -> []142        for card in soup.select(".real-estate-list .real-estate-box"):143            try:144                self._parse_card(card, listings)145            except Exception:146                continue147        return list(listings.values())148149    # -- carte (plugin realestate) ---------------------------------------------------150    def _parse_card(self, card, listings: dict[str, Listing]) -> None:151        link = card.select_one('a.real-estate-gallery[href*="/immobilier/"]') \152            or card.select_one('a[href*="/immobilier/"]')153        if not link:154            return155        url = link["href"]156        m = re.search(r"/immobilier/([^/?#]+)", url)157        if not m:158            return159        ext_id = unquote(m.group(1)).strip("/")160        if not ext_id or ext_id in listings:161            return162163        infos = card.select_one(".real-estate-infos")164        if not infos:165            return166        type_el = infos.select_one(".type")167        unit_label = type_el.get_text(strip=True) if type_el else ""168        addr_el = infos.select_one(".address")169        address = re.sub(r"\s+", " ",170                         addr_el.get_text(" ", strip=True)) if addr_el else ""171172        # <dl> : Prix (« 700 $ / mois »), Inclus, Disponible le (AAAA-MM-JJ)173        price_el = infos.select_one("dd.prix")174        price_label = re.sub(r"\s+", " ",175                             price_el.get_text(" ", strip=True)) if price_el else ""176        incl_el = infos.select_one("dd.inclus")177        included = incl_el.get_text(" ", strip=True) if incl_el else ""178        libre_el = infos.select_one("dd.libre")179        availability = libre_el.get_text(strip=True) if libre_el else ""180181        # galerie : diaporama en background-image (liste et fiche)182        images: list[str] = []183        for div in card.select(".real-estate-gallery div[style]"):184            m_bg = _BG_URL_RE.search(div.get("style", ""))185            if m_bg:186                u = m_bg.group(1).strip("'\" ")187                if u.startswith("http") and u not in images:188                    images.append(u)189190        amenities = [f"Inclus : {included}"] if included else []191192        lst = Listing(193            source=self.source_id,194            external_id=ext_id,195            url=url,196            title=f"{unit_label} — {address}".strip(" —"),197            address=address,198            city="Saguenay",                   # parc à Chicoutimi (ville de Saguenay)199            unit_type=normalize_unit_type(unit_label),200            price=parse_price(price_label),201            price_label=price_label,202            availability=availability,203            amenities=amenities,204            images=images[:25],205        )206207        key = hashlib.sha1(208            f"{unit_label}|{price_label}|{availability}|{included}"209            .encode("utf-8")).hexdigest()210        try:211            payload = self.detail(ext_id, key,212                                  lambda u=url: self._fetch_detail(u))213            self._apply_detail(lst, payload)214        except Exception:215            pass216        listings[ext_id] = lst217218    # -- fiche détail (/immobilier/<slug>/) --------------------------------------------219    def _fetch_detail(self, url: str) -> dict:220        """Description, caractéristiques, GPS et secteur (lien « Retour »)."""221        if self._fetched >= self.max_details:222            raise RuntimeError("budget de fiches détail atteint")223        self._fetched += 1224        html = self.get(url).text225        soup = BeautifulSoup(html, "html.parser")226        out: dict = {}227228        desc_el = soup.select_one(".real-estate-infos .description")229        if desc_el:230            txt = desc_el.get_text("\n", strip=True)231            out["description"] = re.sub(r"[ \t]+", " ", txt).strip()[:1500]232233        out["characteristics"] = [234            re.sub(r"\s+", " ", li.get_text(" ", strip=True))235            for li in soup.select("ul.characteristics li")236            if li.get_text(strip=True)][:20]237238        # secteur : lien « Retour » vers la taxonomie /location/<slug>/239        back = soup.select_one('.real-estate-return a[href*="/location/"]')240        if back:241            m = re.search(r"/location/([^/?#]+)", back["href"])242            if m and m.group(1) != "tous":243                slug = m.group(1)244                out["sector"] = _SECTORS.get(245                    slug, slug.replace("-", " ").strip().title())246247        m = _MAP_LATLNG_RE.search(html)248        if m:249            out["lat"], out["lng"] = float(m.group(1)), float(m.group(2))250251        # galerie pleine taille de la fiche (si plus complète que la liste)252        images: list[str] = []253        for div in soup.select(".real-estate-gallery div[style]"):254            m_bg = _BG_URL_RE.search(div.get("style", ""))255            if m_bg:256                u = m_bg.group(1).strip("'\" ")257                if u.startswith("http") and u not in images:258                    images.append(u)259        out["images"] = images[:25]260        return out261262    def _apply_detail(self, lst: Listing, d: dict) -> None:263        """Reporte le payload (frais ou en cache) sur l'annonce."""264        if not d:265            return266        if d.get("description"):267            lst.description = d["description"]268        if d.get("characteristics"):269            lst.amenities = list(dict.fromkeys(lst.amenities + d["characteristics"]))270        if d.get("sector"):271            lst.sector = d["sector"]272        if d.get("lat") is not None and d.get("lng") is not None:273            lst.lat, lst.lng = d["lat"], d["lng"]274        if d.get("images") and len(d["images"]) > len(lst.images):275            lst.images = d["images"]276
Files main
Menu

Theme