SPB Git

Repository Public

acceslogis_gb.py 9.6 KB 246 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/acceslogis_gb.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/acceslogis_gb.py : connecteur Accès Logis GB (acceslogisgb.com)91#   Gestionnaire de Lanaudière/Mauricie (Joliette, Ste-Élisabeth,92#   St-Ambroise-de-Kildare, Shawinigan…). Site builder mono-page : les cartes93#   « LOGEMENTS DISPONIBLES » vivent dans des grilles .columnswithgap-0294#   (titre <p.font-026><b>, photo, description <p.font-014> qui se termine par95#   « Disponible … » + « 1150$ PAR MOIS »). Aucune page détail ni URL par96#   annonce : external_id = slug du titre + repère d'étage tiré de la97#   description (les titres se répètent d'un étage à l'autre). 1 requête/sync.98# -----------------------------------------------------------------------------99from __future__ import annotations100101import hashlib102import re103import unicodedata104105from bs4 import BeautifulSoup106107from ..schema import Listing, normalize_unit_type, parse_price108from .base import BaseConnector109110BASE = "https://acceslogisgb.com"111LIST_URL = f"{BASE}/"112113# villes desservies (clé sans accents, en minuscules -> nom canonique)114_CITIES = [115    ("ste-elisabeth", "Sainte-Élisabeth"),116    ("sainte-elisabeth", "Sainte-Élisabeth"),117    ("sainte-elizabeth", "Sainte-Élisabeth"),118    ("st-ambroise", "Saint-Ambroise-de-Kildare"),119    ("saint-ambroise", "Saint-Ambroise-de-Kildare"),120    ("shawinigan", "Shawinigan"),121    ("joliette", "Joliette"),122    ("crabtree", "Crabtree"),123    ("berthier", "Berthierville"),124    ("st-thomas", "Saint-Thomas"),125    ("saint-thomas", "Saint-Thomas"),126    ("st-come", "Saint-Côme"),127    ("saint-come", "Saint-Côme"),128]129130# repère d'étage dans la description (« en demi sous-sol », « au 2e étage »…)131_FLOOR_RE = re.compile(132    r"(demi[- ]sous[- ]sol|sous[- ]sol|rez[- ]de[- ]chauss[ée]e|\d+\s*(?:er|e|ème|ieme)\s*étage)",133    re.I)134135136def _strip_accents(s: str) -> str:137    return "".join(c for c in unicodedata.normalize("NFD", s)138                   if unicodedata.category(c) != "Mn")139140141def _slug(s: str) -> str:142    s = _strip_accents(s.lower())143    s = re.sub(r"[^a-z0-9]+", "-", s)144    return s.strip("-")145146147class AccesLogisGBConnector(BaseConnector):148    source_id = "acceslogis_gb"149    request_delay = 0.7150151    def fetch(self) -> list[Listing]:152        resp = self.get(LIST_URL)153        resp.encoding = "utf-8"       # le serveur ne déclare pas le charset154        html = resp.text155        soup = BeautifulSoup(html, "html.parser")156        listings: dict[str, Listing] = {}157        for grid in soup.select("div.columnswithgap-02"):158            for col in grid.find_all("div", recursive=False):159                try:160                    self._parse_card(col, listings)161                except Exception:162                    continue163        return list(listings.values())164165    def _parse_card(self, col, listings: dict[str, Listing]) -> None:166        title_el = col.select_one("p.font-026 b")167        if not title_el:168            return169        title = re.sub(r"\s+", " ", title_el.get_text(" ", strip=True))170        # hors périmètre logement : mini-entrepôts, locaux171        if re.search(r"entrep[oô]t|commercial|local\b", title, re.I):172            return173174        desc_el = col.select_one("p.font-014")175        availability, price_label = "", ""176        description = ""177        if desc_el:178            # les mentions « Disponible … » et « 1150$ » sont des <span> en fin179            # de paragraphe : on les extrait puis on garde le reste en description180            for span in desc_el.find_all("span"):181                t = re.sub(r"\s+", " ", span.get_text(" ", strip=True))182                if re.match(r"(?i)disponible|libre", t):183                    availability = t184                elif re.search(r"\d\s*\$", t):185                    price_label = t186                span.extract()187            description = re.sub(r"\s+", " ", desc_el.get_text(" ", strip=True))188            description = re.sub(r"\bPAR MOIS\b\s*$", "", description).strip()189190        # ville : depuis le titre, sinon la description191        low = _strip_accents(f"{title} {description}".lower())192        city = ""193        for key, name in _CITIES:194            if key in low:195                city = name196                break197198        # type d'unité : titre (« 3 1/2, … ») sinon description199        unit_type = normalize_unit_type(title)200        if not re.fullmatch(r"\d½|6½\+|Studio|Loft|Chambre|Maison|Condo",201                            unit_type or ""):202            unit_type = normalize_unit_type(description)203            if not re.fullmatch(r"\d½|6½\+|Studio|Loft|Chambre|Maison|Condo",204                                unit_type or ""):205                unit_type = ""206207        # adresse civique si mentionnée (« situé au 2510 Rang du Ruisseau à … »)208        address = ""209        m = re.search(r"situ[ée]e?\s+au\s+([\d][^.,]*?)\s+à\s", description)210        if m:211            address = m.group(1).strip()212        elif re.match(r"\d+\s+\w", title) and not normalize_unit_type(title).endswith("½"):213            address = title.split(",")[0].strip()   # le titre est une adresse civique214215        # external_id stable : slug du titre + repère d'étage (les titres se216        # répètent entre étages d'un même immeuble)217        ext = _slug(title)218        m_fl = _FLOOR_RE.search(description)219        if m_fl:220            ext += "-" + _slug(m_fl.group(1))221        if ext in listings:                    # ultime repli : hash du texte222            ext += "-" + hashlib.sha1(description.encode("utf-8")).hexdigest()[:6]223224        images: list[str] = []225        img = col.select_one("img[src]")226        if img:227            src = img["src"]228            if not src.startswith("http"):229                src = f"{BASE}/{src.lstrip('/')}"230            images.append(src)231232        listings[ext] = Listing(233            source=self.source_id,234            external_id=ext,235            url=f"{LIST_URL}#logements",236            title=title,237            address=address,238            city=city,239            unit_type=unit_type,240            price=parse_price(price_label),241            price_label=price_label,242            availability=availability,243            description=description[:900],244            images=images,245        )246
Files main
Menu

Theme