SPB Git

Repository Public

iparc.py 11.2 KB 281 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/iparc.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-2513# Last Modified    : 2026-08-2514#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/iparc.py : connecteur iParc (iparc.ca) — logements à louer à91#   Montréal. WordPress + plugin Estatik (type « property » non exposé au92#   REST) : on parcourt les pages de la catégorie /property-category/a-louer/93#   (+ /page/N/) dont les cartes .es-listing portent data-post-id (external_id94#   stable) et le lien /property/<slug>/. La fiche fournit les champs Estatik95#   (« Taille : 4 1/2 », Chambres, Salle de bain), le prix (.es-price), les96#   équipements/caractéristiques, les coordonnées GPS (data-latitude/97#   longitude), la galerie (wp-content/uploads, miniatures -WxH retirées) et98#   une description bilingue avec l'adresse (📍 …) et la disponibilité.99#   Fiches via le cache détail (clé = hash du texte de la carte).100# -----------------------------------------------------------------------------101from __future__ import annotations102103import hashlib104import re105106from bs4 import BeautifulSoup107108from ..schema import Listing, normalize_unit_type, parse_price109from .base import BaseConnector110111BASE = "https://iparc.ca"112CAT_URL = f"{BASE}/property-category/a-louer/"113_MAX_PAGES = 10                          # garde-fou pagination114115FIELD_RE = re.compile(r"^([^:]{2,30})\s*:\s*(.+)$", re.S)116# adresse civique après le 📍 (doit commencer par un numéro)117ADDR_RE = re.compile(r"📍\s*(\d[\w\s.,'°é½-]{5,80}?)\s*[–—(]")118DISPO_RE = re.compile(119    r"Disponible\s*(?:le\s*)?(?:immédiatement|d[èe]s maintenant"120    r"|\d{1,2}\s*(?:er)?\s*(?:janvier|février|mars|avril|mai|juin|juillet"121    r"|août|septembre|octobre|novembre|décembre)(?:\s*20\d\d)?)", re.I)122# repli adresse : « 5187 rue Berri », « 6050, 30e Avenue »…123ADDR_FALLBACK_RE = re.compile(124    r"(\d{2,5}(?:\s*,)?\s+(?:rue|avenue|av\.|boulevard|boul\.|chemin|ch\.|"125    r"place|\d{1,2}e\s+Avenue)\s*[A-ZÀ-Ü0-9][\w'’.é½-]*(?:\s+[A-ZÀ-Ü][\w'’é-]+)?)")126THUMB_RE = re.compile(r"-\d+x\d+(\.\w+)$")127IMG_BAD_RE = re.compile(r"logo|icon|favicon|iparc20\d\d", re.I)128129130class IparcConnector(BaseConnector):131    source_id = "iparc"132    request_delay = 0.7133134    def fetch(self) -> list[Listing]:135        listings: list[Listing] = []136        seen: set[str] = set()137        for page in range(1, _MAX_PAGES + 1):138            url = CAT_URL if page == 1 else f"{CAT_URL}page/{page}/"139            try:140                html = self.get(url).text141            except Exception:142                break                    # 404 = fin de la pagination143            soup = BeautifulSoup(html, "html.parser")144            cards = soup.select(".es-listing[data-post-id]")145            if not cards:146                break147            for card in cards:148                try:149                    pid = str(card["data-post-id"])150                    if pid in seen:151                        continue152                    seen.add(pid)153                    a = card.find("a", href=re.compile(r"/property/"))154                    if not a:155                        continue156                    href = a["href"]157                    card_text = card.get_text(" ", strip=True)158                    key = hashlib.sha1(159                        card_text.encode("utf-8")).hexdigest()160                    d = self.detail(pid, key,161                                    lambda h=href: self._property(h))162                    lst = self._listing(pid, href, d)163                    if lst:164                        listings.append(lst)165                except Exception:166                    continue167        return listings168169    def _property(self, url: str) -> dict:170        """Scrape la fiche Estatik : champs, prix, GPS, galerie, description."""171        out: dict = {"title": "", "price": "", "fields": {}, "desc": "",172                     "amenities": [], "lat": None, "lng": None, "images": []}173        page = self.get(url).text174        soup = BeautifulSoup(page, "html.parser")175        if soup.h1:176            out["title"] = soup.h1.get_text(" ", strip=True)177        pr = soup.select_one(".es-price")178        if pr:179            out["price"] = pr.get_text(" ", strip=True)180        for f in soup.select(".es-property-field"):181            t = re.sub(r"\s+", " ", f.get_text(" ", strip=True))182            m = FIELD_RE.match(t)183            if not m:184                continue185            label, value = m.group(1).strip(), m.group(2).strip()186            if label.lower().startswith("la description"):187                out["desc"] = value[:3000]188            elif label.lower().startswith(("équipements",189                                           "caractéristiques")):190                out["amenities"].extend(191                    x.strip() for x in value.split("  ") if x.strip())192            else:193                out["fields"][label] = value194        geo = soup.select_one("[data-latitude][data-longitude]")195        if geo:196            try:197                out["lat"] = float(geo["data-latitude"])198                out["lng"] = float(geo["data-longitude"])199            except (TypeError, ValueError):200                pass201        images = []202        for img in soup.select(".es-single img, .es-mobile-gallery img"):203            u = img.get("src") or img.get("data-lazy") or ""204            if not u.startswith("http") or "/uploads/" not in u \205                    or IMG_BAD_RE.search(u):206                continue207            u = THUMB_RE.sub(r"\1", u)   # miniature -> pleine taille208            if u not in images:209                images.append(u)210        out["images"] = images[:15]211        return out212213    def _listing(self, pid: str, url: str, d: dict) -> Listing | None:214        fields = d.get("fields", {})215        desc = d.get("desc", "")216        title = d.get("title") or ""217218        taille = fields.get("Taille", "")219        unit_type = normalize_unit_type(taille) if taille else ""220        bedrooms = bathrooms = None221        try:222            if fields.get("Chambres"):223                bedrooms = float(fields["Chambres"])224        except ValueError:225            pass226        try:227            if fields.get("Salle de bain"):228                bathrooms = float(fields["Salle de bain"])229        except ValueError:230            pass231232        address = ""233        am = ADDR_RE.search(desc) or ADDR_FALLBACK_RE.search(desc)234        if am:235            address = re.sub(r"\s+,", ",", am.group(1)).strip()236        availability = ""237        dm = DISPO_RE.search(desc)238        if dm:239            availability = re.sub(r"\s+", " ", dm.group(0)).strip()240241        sector = ""242        poi = fields.get("centre d'intéret") or fields.get("centre d'intérêt")243        if poi:244            premier = poi.split(",")[0].strip()245            # noms propres seulement (écarte « commerces », « métro »…)246            if premier[:1].isupper():247                sector = premier248249        amenities = list(dict.fromkeys(d.get("amenities", [])))250        pieces = fields.get("Nombre de pièces")251        if pieces:252            amenities.append(f"{pieces} pièces")253        furnished = None254        blob = " ".join(amenities).lower()255        if "non meublé" in blob:256            furnished = False257        elif "meublé" in blob or "meublé" in title.lower():258            furnished = True259260        return Listing(261            source=self.source_id,262            external_id=pid,263            url=url,264            title=title,265            address=address,266            sector=sector,267            city="Montréal",268            unit_type=unit_type,269            bedrooms=bedrooms,270            bathrooms=bathrooms,271            price=parse_price(d.get("price", "")),272            price_label=d.get("price", ""),273            availability=availability,274            furnished=furnished,275            description=desc,276            amenities=amenities,277            images=d.get("images", []),278            lat=d.get("lat"),279            lng=d.get("lng"),280        )281
Files main
Menu

Theme