SPB Git

Repository Public

cite_immobilier.py 8.1 KB 190 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/cite_immobilier.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/cite_immobilier.py : connecteur Cité Immobilier (citeimmobilier.com)91#   224 logements à Victoriaville. Site GoDaddy Website Builder 8 (même famille92#   que capital_rdr) mais SANS annonces par unité : la page /immeubles liste les93#   immeubles (cartes data-ux="ContentBasic", titres data-aid ABOUT_HEADLINE_*)94#   avec adresse civique, description et un bouton d'état — « APPARTEMENT À95#   LOUER » (vacance) ou « - COMPLET - ». On publie une annonce par immeuble96#   résidentiel affichant une vacance ; prix/type ne sont pas publiés.97#   robots.txt : « User-agent: * » sans Disallow (tout permis).98# -----------------------------------------------------------------------------99from __future__ import annotations100101import re102103from bs4 import BeautifulSoup104105from ..schema import Listing, strip_accents106from .base import BaseConnector107108BASE = "https://citeimmobilier.com"109LIST_URL = f"{BASE}/immeubles"110111112def _slug(text: str) -> str:113    """« 540 rue Notre-Dame Est » -> « 540-rue-notre-dame-est » (id stable)."""114    s = strip_accents(text.lower())115    return re.sub(r"-{2,}", "-", re.sub(r"[^a-z0-9]+", "-", s)).strip("-")116117118class CiteImmobilierConnector(BaseConnector):119    source_id = "cite_immobilier"120    request_delay = 0.7121122    def fetch(self) -> list[Listing]:123        html = self.get(LIST_URL).text124        soup = BeautifulSoup(html, "html.parser")125126        listings: list[Listing] = []127        seen: set[str] = set()128        for section in soup.select('section[data-ux="Section"]'):129            sec_title = section.select_one('[data-aid="ABOUT_SECTION_TITLE_RENDERED"]')130            sec_name = sec_title.get_text(" ", strip=True) if sec_title else ""131            # seules les sections résidentielles nous intéressent132            # (« IMMEUBLES RÉSIDENTIELS », « IMMEUBLES COMMERCIAUX ET RÉSIDENTIELS »)133            if "RÉSIDENTIEL" not in sec_name.upper():134                continue135136            for card in section.select('[data-ux="ContentBasic"]'):137                head = card.select_one('[data-aid^="ABOUT_HEADLINE"]')138                if not head:139                    continue140                address = head.get_text(" ", strip=True)141                ext_id = _slug(address)142                if not ext_id or ext_id in seen:143                    continue144145                card_text = card.get_text(" ", strip=True)146                ctas = [a.get_text(" ", strip=True)147                        for a in card.find_all("a") if a.get_text(strip=True)]148                # vacance affichée = bouton « APPARTEMENT À LOUER » ;149                # « - COMPLET - » ou absence du bouton → immeuble plein, ignoré150                avail = next((c for c in ctas151                              if re.search(r"appartement.*louer", c, re.I)), "")152                if not avail or re.search(r"-\s*COMPLET\s*-", card_text):153                    continue154                seen.add(ext_id)155156                # description : paragraphes de la carte (texte source),157                # sans le libellé du bouton158                lines = []159                for p in card.find_all(["p", "h5"]):160                    t = re.sub(r"\s+", " ", p.get_text(" ", strip=True))161                    if t and t not in lines and t.upper() != avail.upper():162                        lines.append(t)163164                images: list[str] = []165                img = card.select_one("img[src], img[srcset]")166                if img:167                    src = img.get("src") or (img.get("srcset") or "").split(" ")[0]168                    if src.startswith("//"):169                        src = "https:" + src170                    if src.startswith("http"):171                        images.append(src)172173                listings.append(Listing(174                    source=self.source_id,175                    external_id=ext_id,      # slug de l'adresse de l'immeuble176                    url=f"{LIST_URL}#{ext_id}",   # pas de fiche individuelle177                    title=f"Appartement à louer — {address}",178                    address=address,179                    sector="",180                    # tout le parc Cité Immobilier (224 logements + Le Quartz)181                    # est à Victoriaville (centre-ville, cf. page Immeubles)182                    city="Victoriaville",183                    unit_type="",            # jamais publié par la source184                    price_label="",          # jamais publié par la source185                    availability=avail,      # texte du bouton (source)186                    description="\n".join(lines)[:900],187                    images=images,188                ))189        return listings190
Files main
Menu

Theme