SPB Git

Repository Public

immeubles_guillot.py 10.6 KB 254 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/immeubles_guillot.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0813# Last Modified    : 2026-08-0814#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/immeubles_guillot.py : connecteur Les Immeubles Guillot91#   (immeublesguillot.com) — 3 immeubles / 61 unités à Québec :92#     - Ader (Beauport, 7 unités, 7½)93#     - Boul. Ste-Anne (Beauport, 28 unités, 1½/3½/4½)94#     - des Cyprès (Charlesbourg, 26 unités, 3½/4½/5½)95#   Site WordPress rendu serveur : une page par immeuble avec l'adresse,96#   les types offerts (« Types d'appartements dans cet immeuble »), un97#   tableau de commodités (colonnes Logement / Immeuble / Quartier) et des98#   galeries « Appartement modèle » par type. Aucun prix ni disponibilité99#   affichés -> price=None, availability vide (rien d'inventé).100#   Granularité = immeuble × type d'appartement (comme utile.py).101# -----------------------------------------------------------------------------102from __future__ import annotations103104import re105106from bs4 import BeautifulSoup107108from ..schema import Listing109from .base import BaseConnector110111BASE = "https://immeublesguillot.com"112INDEX_URL = f"{BASE}/appartements-a-louer/"113114# images de contenu (uploads) ; icônes/logos exclus115_SKIP_IMG = re.compile(r"/icon-|logo|favicon|-\d{2,4}x\d{2,4}\.", re.I)116_TYPE_RE = re.compile(r"^\d\s*(?:1/2|½)$")117_ADDR_RE = re.compile(r"G\d[A-Z]\s?\d[A-Z]\d", re.I)   # code postal québécois118119120def _type_slug(t: str) -> str:121    return re.sub(r"[^a-z0-9]+", "-", t.lower().replace("½", "1-2")).strip("-")122123124class ImmeublesGuillotConnector(BaseConnector):125    source_id = "immeubles_guillot"126    request_delay = 0.6127    max_buildings = 10       # garde-fou128    max_images = 12129130    def fetch(self) -> list[Listing]:131        index = self.get(INDEX_URL).text132        slugs = list(dict.fromkeys(133            re.findall(r'href="https?://immeublesguillot\.com'134                       r'/appartements-a-louer/([a-z0-9\-]+)/"', index)))135        listings: list[Listing] = []136        for slug in slugs[: self.max_buildings]:137            try:138                listings.extend(self._building(slug))139            except Exception:140                continue141        return listings142143    # -- une page d'immeuble ----------------------------------------------------144    def _building(self, slug: str) -> list[Listing]:145        url = f"{BASE}/appartements-a-louer/{slug}/"146        html = self.get(url).text147        soup = BeautifulSoup(html, "html.parser")148149        # nom affiché : dernier élément du fil d'Ariane (« Beauport / Ader »)150        name = slug151        crumb = soup.select_one(".breadcrumbs, #breadcrumbs, .nectar-breadcrumbs")152        if crumb:153            parts = [t.strip() for t in crumb.get_text("»").split("»")154                     if t.strip()]155            if parts:156                name = parts[-1]157        sector = name.split("/")[0].strip() if "/" in name else ""158159        # adresse : titre contenant un code postal (« 3608 Boul. Ste-Anne,160        # Québec, G1E 3M1 »)161        address = ""162        for h in soup.find_all(["h1", "h2", "h3", "h4"]):163            t = re.sub(r"\s+", " ", h.get_text(" ", strip=True))164            if _ADDR_RE.search(t):165                address = t166                break167168        # types offerts : <p> qui suit « Types d'appartements dans cet immeuble »169        types: list[str] = []170        for h3 in soup.find_all(["h3", "h2"]):171            if "types d" not in h3.get_text(strip=True).lower():172                continue173            p = h3.find_next("p")174            if p:175                for line in p.get_text("\n", strip=True).split("\n"):176                    line = re.sub(r"\s+", " ", line).strip()177                    if _TYPE_RE.match(line) and line not in types:178                        types.append(line)179            break180181        # commodités : tableau tablepress (colonnes Logement et Immeuble ;182        # la colonne Quartier décrit le voisinage, pas le logement)183        amenities: list[str] = []184        for td in soup.select("table.tablepress td.column-2, "185                              "table.tablepress td.column-4"):186            for line in td.get_text("\n", strip=True).split("\n"):187                t = re.sub(r"\s+", " ", line).strip()188                if 3 <= len(t) <= 90 and t not in amenities:189                    amenities.append(t)190191        # description : premiers paragraphes après l'adresse192        desc_parts: list[str] = []193        for p in soup.find_all("p"):194            t = re.sub(r"\s+", " ", p.get_text(" ", strip=True))195            if len(t) >= 80 and not p.find_parent(("footer", "nav")):196                desc_parts.append(t)197            if len(desc_parts) >= 2:198                break199        description = " ".join(desc_parts)[:600]200201        # galeries « Appartement modèle – X 1/2 » : photos par type ;202        # repli : toutes les photos de la page203        all_photos = [u for u in dict.fromkeys(re.findall(204            r'https://immeublesguillot\.com/wp-content/uploads/'205            r'[^"\s]+\.(?:jpe?g|webp|png)', html))206            if not _SKIP_IMG.search(u)]207        by_type: dict[str, list[str]] = {}208        for h2 in soup.find_all("h2"):209            head = re.sub(r"\s+", " ", h2.get_text(" ", strip=True))210            m = re.match(r"Appartement modèle(?:\s*[–-]\s*(\d\s*1/2))?",211                         head, re.I)212            if not m:213                continue214            key = re.sub(r"\s+", " ", m.group(1)).strip() if m.group(1) else ""215            gallery = h2.find_parent("div", class_="wpb_wrapper")216            root = (gallery.find_parent("div", class_="vc_column-inner")217                    or gallery) if gallery else h2.parent218            imgs = []219            # la galerie lie chaque vignette (-600x375) à l'original plein format220            for a in root.select('a[href*="/wp-content/uploads/"]'):221                href = a.get("href") or ""222                if (href.startswith("http") and not _SKIP_IMG.search(href)223                        and re.search(r"\.(?:jpe?g|webp|png)$", href, re.I)224                        and href not in imgs):225                    imgs.append(href)226            for img in root.find_all("img"):227                src = img.get("src") or img.get("data-src") or ""228                if (src.startswith("http") and not _SKIP_IMG.search(src)229                        and src not in imgs):230                    imgs.append(src)231            if imgs:232                by_type[key] = imgs[: self.max_images]233234        out: list[Listing] = []235        for t in types:236            images = by_type.get(t) or by_type.get("") or all_photos237            out.append(Listing(238                source=self.source_id,239                external_id=f"{slug}-{_type_slug(t)}",240                url=url,241                title=f"Immeubles Guillot — {name} ({t})",242                address=address,243                sector=sector,244                city="Québec",245                unit_type=t,246                price=None,              # aucun prix affiché sur le site247                price_label="",248                availability="",         # aucune disponibilité affichée249                description=description,250                amenities=list(amenities),251                images=list(images)[: self.max_images],252            ))253        return out254
Files main
Menu

Theme