SPB Git

Repository Public

per.py 9.7 KB 240 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/per.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0613# 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/per.py : connecteur Les Immeubles Paul-E. Richard91#   (immeublesper.com — 18 immeubles à Limoilou, Charlesbourg et Beauport).92#   Les unités en vedette sont listées sur /logements/ ; chaque fiche93#   /logement/<slug>/ fournit secteur, adresse, format, prix, disponibilité,94#   caractéristiques et galerie de photos.95# -----------------------------------------------------------------------------96from __future__ import annotations9798import re99100from bs4 import BeautifulSoup101102from ..schema import Listing, infer_city, normalize_unit_type, parse_price103from .base import BaseConnector104105BASE = "https://immeublesper.com"106LIST_URL = f"{BASE}/logements/"107108_SIZE_SUFFIX = re.compile(r"-\d{2,4}x\d{2,4}(?=\.(?:jpg|jpeg|png|webp)$)", re.I)109_IMG_BLACKLIST = re.compile(r"ico-|logo|slide-\d|favicon", re.I)110111112class PERConnector(BaseConnector):113    source_id = "per"114    request_delay = 0.6115    max_details = 60        # garde-fou de fetch des fiches116117    def fetch(self) -> list[Listing]:118        html = self.get(LIST_URL).text119        slugs: list[str] = []120        for m in re.finditer(r'href="https://immeublesper\.com/logement/([^/"]+)/?"', html):121            if m.group(1) not in slugs:122                slugs.append(m.group(1))123124        listings: list[Listing] = []125        for slug in slugs[:self.max_details]:126            try:127                lst = self._parse_detail(slug)128                if lst:129                    listings.append(lst)130            except Exception:131                continue132        return listings133134    # -- fiche /logement/<slug>/ -------------------------------------------------135    def _parse_detail(self, slug: str) -> Listing | None:136        url = f"{BASE}/logement/{slug}/"137        html = self.get(url).text138        soup = BeautifulSoup(html, "html.parser")139140        # Informations générales : paires "ls-label"/"ls-data"141        info: dict[str, str] = {}142        for div in soup.select("div.ls-info"):143            label = div.select_one("span.ls-label")144            data = div.select_one("span.ls-data")145            if label and data:146                key = label.get_text(strip=True).rstrip(":").lower()147                info[key] = data.get_text(" ", strip=True)148149        unit_raw = info.get("format", "")150        # exclusions : stationnement / commercial / rangement151        blob = " ".join([slug, unit_raw] + list(info.values()))152        if re.search(r"stationnement|commercial|rangement|garage|entrep[oô]t",153                     unit_raw + " " + slug, re.I):154            return None155156        sector = info.get("secteur", "")157        address = info.get("adresse", "")158        price_label = info.get("prix", "")159        availability = info.get("disponibilité", info.get("disponibilite", ""))160161        # numéro d'unité : texte "#3" entre les ls-info162        unit_no = ""163        details_div = soup.select_one("div.ls-single-details")164        if details_div:165            m = re.search(r"#\s*([\w\-]+)", details_div.get_text(" ", strip=True))166            if m:167                unit_no = f"#{m.group(1)}"168169        # caractéristiques170        amenities: list[str] = []171        for h2 in soup.find_all("h2"):172            if "caract" in h2.get_text(strip=True).lower():173                ul = h2.find_next("ul")174                if ul:175                    for li in ul.find_all("li"):176                        t = re.sub(r"\s+", " ", li.get_text(" ", strip=True))177                        if t and not t.startswith("N.B.") and t not in amenities:178                            amenities.append(t)179                break180        for key, lbl in (("nombre de chambres", "chambre(s)"),181                         ("étage", "étage"), ("etage", "étage")):182            if info.get(key):183                amenities.append(f"{info[key]} {lbl}")184185        # Animaux : champ structuré "Animaux permis: Oui/Non" de la fiche.186        # Valeur explicite (prioritaire sur la dérivation) — le texte brut187        # "Animaux permis : Non" serait sinon mal lu par la normalisation.188        pets = None189        pets_raw = (info.get("animaux permis") or "").strip()190        if pets_raw:191            amenities.append(f"Animaux permis : {pets_raw}")192            low = pets_raw.lower()193            if low.startswith("non"):194                pets = "non"195            elif low.startswith("oui"):196                pets = "oui"197            else:198                pets = "conditions"199200        # images : galerie fancybox + image principale (pleine taille, dédupliquées)201        images: list[str] = []202        for a in soup.select("div.gallerie a[href], a.fancybox-thumb[href]"):203            u = a.get("href", "")204            if re.search(r"\.(?:jpg|jpeg|png|webp)$", u, re.I):205                u = _SIZE_SUFFIX.sub("", u)206                if u.startswith("/"):207                    u = BASE + u208                if u.startswith("http") and not _IMG_BLACKLIST.search(u) and u not in images:209                    images.append(u)210        main = soup.select_one("div.ls-single-image img[src]")211        if main:212            u = _SIZE_SUFFIX.sub("", main["src"])213            if u.startswith("http") and not _IMG_BLACKLIST.search(u) and u not in images:214                images.insert(0, u)215        if not images:   # repli : toutes les images d'uploads de la page216            for u in re.findall(r'https://immeublesper\.com/wp-content/uploads/'217                                r'[^"\'\s]+\.(?:jpg|jpeg|png|webp)', html, re.I):218                u = _SIZE_SUFFIX.sub("", u)219                if not _IMG_BLACKLIST.search(u) and u not in images:220                    images.append(u)221222        title = ", ".join(x for x in (address or slug.replace("-", " "),223                                      unit_no, unit_raw) if x)224        return Listing(225            source=self.source_id,226            external_id=slug,227            url=url,228            title=title,229            address=address,230            sector=sector,231            city=infer_city(sector, default="Québec"),232            unit_type=normalize_unit_type(unit_raw),233            price=parse_price(price_label),234            price_label=price_label,235            availability=availability,236            pets=pets,237            amenities=amenities,238            images=images[:25],239        )240
Files main
Menu

Theme