SPB Git

Repository Public

gestion_jdm.py 10.3 KB 243 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/gestion_jdm.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/gestion_jdm.py : connecteur JDM Gestion immobilière (gestionjdm.ca91#   — Rivière-du-Loup, Témiscouata-sur-le-Lac, Cacouna ; Bas-Saint-Laurent).92#   WordPress + Elementor (widget UAEL Posts) rendu serveur :93#     - page /logement/ : cartes `.uael-post-wrapper.logement` — badge94#       d'étiquette (« Disponible »), adresse complète en extrait95#       (« 36 rue plourde, Rivière-du-Loup (QC) G5R 1A1 »), photo, lien fiche ;96#     - fiche (/logement-1/…) : sections h4 « Description » (text-editor),97#       « Caractéristiques » et « À proximité » (icon-list), galerie.98#   Granularité IMMEUBLE (« 24 unités de logements sur 3 étages ») — précédent99#   girs/immeubles_guillot : aucun prix ni liste d'unités publiés -> price=None,100#   rien d'inventé. Les cartes étiquetées « loué / indisponible » (si elles101#   apparaissent un jour) sont écartées ; le badge brut alimente availability.102#   Le type n'est retenu que si UN seul est cité (« 3-1/2, 4-1/2 et 5-1/2 » ->103#   vide, la description fait foi). Les pages /chambre/ (maisons de chambres)104#   et /commercial/ ne sont pas visitées.105#   external_id stable : slug de la fiche (logement-1).106#   robots.txt ouvert (Disallow vide), sitemap Yoast public.107# -----------------------------------------------------------------------------108from __future__ import annotations109110import re111112from bs4 import BeautifulSoup113114from ..schema import Listing115from .base import BaseConnector116117BASE = "https://gestionjdm.ca"118LIST_URL = f"{BASE}/logement/"119120_TYPE_RE = re.compile(r"([1-9])\s*[-\s]?\s*(?:½|1/2)")121_CITY_RE = re.compile(r",\s*([^,()]+?)\s*\(QC\)", re.I)122_SKIP_STATUS = re.compile(r"(?i)lou[ée]|indisponible|non\s+disponible")123124125class GestionJdmConnector(BaseConnector):126    source_id = "gestion_jdm"127    request_delay = 0.6128    max_images = 10129130    def fetch(self) -> list[Listing]:131        soup = BeautifulSoup(self.get(LIST_URL).text, "html.parser")132        listings: dict[str, Listing] = {}133        for card in soup.select("div.uael-post-wrapper"):134            try:135                self._parse_card(card, listings)136            except Exception:137                continue138        return list(listings.values())139140    # -- carte UAEL Posts ----------------------------------------------------------141    def _parse_card(self, card, listings: dict[str, Listing]) -> None:142        link = card.select_one("a[href]")143        if link is None:144            return145        url = link["href"].strip()146        m = re.search(r"gestionjdm\.ca/([^/?#]+)", url)147        if not m:148            return149        ext_id = m.group(1)150        if ext_id in listings:151            return152153        # adresse complète en extrait (« 52 rue de l'Anse, Témiscouata… (QC) G0L 1E0 »)154        excerpt = card.select_one(".uael-post__excerpt")155        address = re.sub(r"\s+", " ",156                         excerpt.get_text(" ", strip=True)) if excerpt else ""157        m_city = _CITY_RE.search(address)158        city = m_city.group(1).strip() if m_city else ""159160        # badge d'étiquette (« Disponible ») — brut ; cartes louées écartées161        badge = card.select_one(".uael-post__terms")162        availability = re.sub(r"\s+", " ",163                              badge.get_text(" ", strip=True)) if badge else ""164        if _SKIP_STATUS.search(availability):165            return166167        images: list[str] = []168        thumb = card.select_one(".uael-post__thumbnail img[src]")169        if thumb and thumb["src"].startswith("http"):170            images.append(thumb["src"])171172        # fiche (cache : re-fetch seulement si adresse/badge changent)173        payload = self.detail(ext_id, f"{address}|{availability}",174                              lambda: self._fetch_detail(url))175        description = payload.get("description", "")176        amenities = payload.get("amenities", [])177        for u in payload.get("images", []):178            if u not in images and len(images) < self.max_images:179                images.append(u)180181        # type d'unités : seulement si UN seul type est cité en prose182        types = sorted(set(_TYPE_RE.findall(f"{description} "183                                            f"{' '.join(amenities)}")))184        unit_type = f"{types[0]}½" if len(types) == 1 else ""185186        listings[ext_id] = Listing(187            source=self.source_id,188            external_id=ext_id,189            url=url,190            title=address or ext_id,191            address=address,192            city=city,193            unit_type=unit_type,194            price=None,                    # aucun loyer publié sur le site195            price_label="",196            availability=availability,197            description=description,198            amenities=amenities,199            images=images,200        )201202    # -- fiche (/logement-<n>/) ------------------------------------------------------203    def _fetch_detail(self, url: str) -> dict:204        soup = BeautifulSoup(self.get(url).text, "html.parser")205        out: dict = {"description": "", "amenities": [], "images": []}206207        paras: list[str] = []208        nearby: list[str] = []209        for h4 in soup.select("h4.elementor-heading-title"):210            section = h4.get_text(" ", strip=True).lower()211            widget = h4.find_parent("div", class_="elementor-widget-heading")212            nxt = widget.find_next_sibling("div") if widget else None213            if nxt is None:214                continue215            if section.startswith("description"):216                paras += [re.sub(r"\s+", " ", p.get_text(" ", strip=True))217                          for p in nxt.select("p")]218                if not nxt.select("p"):      # texte sans <p>219                    paras.append(re.sub(r"\s+", " ",220                                        nxt.get_text(" ", strip=True)))221            elif section.startswith("caractéristiques"):222                out["amenities"] = [223                    re.sub(r"\s+", " ", li.get_text(" ", strip=True))224                    for li in nxt.select("li") if li.get_text(strip=True)]225            elif section.startswith("à proximité"):226                nearby = [re.sub(r"\s+", " ", li.get_text(" ", strip=True))227                          for li in nxt.select("li") if li.get_text(strip=True)]228229        description = "\n".join(t for t in paras if t)[:1400]230        if nearby:231            description = (description + "\nÀ proximité : "232                           + ", ".join(nearby)).strip()233        out["description"] = description234235        for img in soup.select("img[src*='/wp-content/uploads/']"):236            u = img["src"]237            if (u.startswith("http") and "logo" not in u.lower()238                    and u not in out["images"]):239                out["images"].append(u)240                if len(out["images"]) >= self.max_images:241                    break242        return out243
Files main
Menu

Theme