SPB Git

Repository Public

gestion_valco.py 8.7 KB 211 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/gestion_valco.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_valco.py : connecteur Gestion Valco (gestionvalco.ca)91#   WordPress Divi/Elementor, page « Logements à louer » rédigée à la main :92#   chaque logement = une section Elementor « titre » (« 402 Laviolette93#   Trois-Rivières 4 1/2 »), suivie d'un bloc texte (inclusions, dispo…)94#   et de galeries d'images. 1 seule requête par sync ; external_id =95#   data-id Elementor de la section titre (stable tant que la section vit).96# -----------------------------------------------------------------------------97from __future__ import annotations9899import re100101from bs4 import BeautifulSoup102103from ..schema import Listing, normalize_unit_type104from .base import BaseConnector105106BASE = "https://gestionvalco.ca"107LIST_URL = f"{BASE}/logements-a-louer/"   # redirige vers /elementor-344/logements-a-louer/108109# titre d'annonce : contient un type d'unité (« 4 1/2 », « 3½ », studio…)110_TYPE_RE = re.compile(r"\d\s*(?:½|1/2)|studio|loft", re.I)111# villes desservies par Gestion Valco (Mauricie / Centre-du-Québec)112_CITIES = [113    ("trois-rivieres", "Trois-Rivières"),114    ("trois- rivieres", "Trois-Rivières"),115    ("cap-de-la-madeleine", "Trois-Rivières"),116    ("shawinigan", "Shawinigan"),117    ("nicolet", "Nicolet"),118    ("louiseville", "Louiseville"),119    ("st-narcisse", "Saint-Narcisse"),120    ("saint-narcisse", "Saint-Narcisse"),121]122123124def _norm(txt: str) -> str:125    """Aplatis les <font> de Google Translate : espaces multiples, « Trois- Rivières »."""126    txt = re.sub(r"\s+", " ", txt).strip()127    return re.sub(r"(\w)-\s+(\w)", r"\1-\2", txt)128129130def _strip_accents(s: str) -> str:131    import unicodedata132    return "".join(c for c in unicodedata.normalize("NFD", s)133                   if unicodedata.category(c) != "Mn")134135136class GestionValcoConnector(BaseConnector):137    source_id = "gestion_valco"138    request_delay = 0.7139140    def fetch(self) -> list[Listing]:141        html = self.get(LIST_URL).text   # requests suit la redirection142        soup = BeautifulSoup(html, "html.parser")143        main = soup.find("main") or soup144145        listings: list[Listing] = []146        current: Listing | None = None147        desc_lines: list[str] = []148149        def _flush() -> None:150            nonlocal current, desc_lines151            if current is not None:152                current.description = "\n".join(desc_lines)[:900]153                listings.append(current)154            current, desc_lines = None, []155156        for sec in main.select("section.elementor-top-section"):157            head = sec.select_one(".elementor-widget-heading .elementor-heading-title")158            title = _norm(head.get_text(" ", strip=True)) if head else ""159            if title and _TYPE_RE.search(title) and not re.search(160                    r"commercial|stationnement|rangement|local\b", title, re.I):161                # nouvelle annonce : section titre162                _flush()163                low = _strip_accents(title.lower())164                city, city_pos = "", -1165                for key, name in _CITIES:166                    p = low.find(key)167                    if p >= 0:168                        city, city_pos = name, p169                        break170                # adresse civique : début du titre jusqu'au nom de ville171                address = ""172                if city_pos > 0 and re.match(r"\d", title):173                    address = title[:city_pos].strip(" ,-")174                # disponibilité : mention « Libre … » du titre (texte source)175                m = re.search(r"\b(Libre\b.*)$", title, re.I)176                availability = m.group(1).strip() if m else ""177                ext_id = sec.get("data-id") or ""178                if not ext_id:179                    continue180                current = Listing(181                    source=self.source_id,182                    external_id=str(ext_id),183                    url=f"{BASE}/elementor-344/logements-a-louer/#{ext_id}",184                    title=title,185                    address=address,186                    city=city,187                    unit_type=normalize_unit_type(title),188                    availability=availability,189                )190                # la section titre peut aussi porter le bloc texte : on continue191            if current is None:192                continue193            # même section ou sections suivantes : description (texte), galeries194            for txt in sec.select(".elementor-widget-text-editor"):195                for p in txt.find_all(["p", "li"]) or [txt]:196                    t = re.sub(r"\s+", " ", p.get_text(" ", strip=True))197                    if t and t not in desc_lines:198                        desc_lines.append(t)199                if not current.availability:200                    for t in desc_lines:201                        if re.search(r"\b(libre|disponible)\b", t, re.I):202                            current.availability = t203                            break204            for a in sec.select("a.e-gallery-item[href]"):205                u = a["href"]206                if u.startswith("http") and u not in current.images:207                    current.images.append(u)208            current.images = current.images[:30]209        _flush()210        return listings211
Files main
Menu

Theme