SPB Git

Repository Public

louer_saguenay.py 10.4 KB 248 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/louer_saguenay.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/louer_saguenay.py : connecteur Louer Saguenay (louersaguenay.com91#   — centre-ville de Jonquière, ville de Saguenay ; 9128-0768 Québec inc.).92#   Petit parc de lofts et d'appartements au-dessus de locaux commerciaux de la93#   rue Saint-Dominique. WordPress + Elementor rendu serveur :94#     - page /location-loft-appartement-jonquiere/ : boucle Elementor — un95#       item `.e-loop-item.category-location-loft-appartement-jonquiere` par96#       annonce (titre h2 + lien, extrait « DISPONIBLE AU 1-6-2026 », photo) ;97#       la section « NOS ESPACES COMMERCIALES » (articles `ee-post`, catégorie98#       location-espaces-commercials-saguenay) est ignorée ;99#     - fiche : description (« Informations »), « Prix mensuel : » suivi des100#       tarifs « 1395.00$ (Non meublé) / 1495.00$ (Meublé) » -> price = le plus101#       bas, price_label = texte original complet, galerie de photos.102#   Fiches visitées via self.detail (cache BD, re-fetch seulement si l'extrait103#   ou le titre change) — parc ~5 unités résidentielles.104#   external_id stable : slug de la fiche. city=Saguenay, sector=Jonquière105#   (convention des connecteurs SLSJ existants).106#   robots.txt ouvert (Disallow /imunify-bot-check seulement), sitemap Yoast.107# -----------------------------------------------------------------------------108from __future__ import annotations109110import re111112from bs4 import BeautifulSoup113114from ..schema import Listing, normalize_unit_type115from .base import BaseConnector116117BASE = "https://louersaguenay.com"118LIST_URL = f"{BASE}/location-loft-appartement-jonquiere/"119120_TYPE_RE = re.compile(r"([1-6])\s*(?:½|1/2)")121# « … à louer 2345 rue Saint-Dominique Suite 201 » -> tout ce qui suit « à louer »122_ADDR_RE = re.compile(r"à louer\s+(\d.+)$", re.I)123_PRICE_RE = re.compile(r"(\d[\d\s]*(?:[.,]\d{1,2})?)\s*\$")124125126class LouerSaguenayConnector(BaseConnector):127    source_id = "louer_saguenay"128    request_delay = 0.6129    max_images = 10130131    def fetch(self) -> list[Listing]:132        soup = BeautifulSoup(self.get(LIST_URL).text, "html.parser")133134        listings: dict[str, Listing] = {}135        items = soup.select(136            ".e-loop-item.category-location-loft-appartement-jonquiere")137        for item in items:138            try:139                self._parse_item(item, listings)140            except Exception:141                continue142        return list(listings.values())143144    # -- item de la boucle Elementor ----------------------------------------------145    def _parse_item(self, item, listings: dict[str, Listing]) -> None:146        h2 = item.select_one("h2.elementor-heading-title a[href]")147        if h2 is None:148            return149        url = h2["href"].strip()150        title = re.sub(r"\s+", " ", h2.get_text(" ", strip=True))151        m = re.search(r"louersaguenay\.com/([^/?#]+)", url)152        if not m:153            return154        ext_id = m.group(1)155        if ext_id in listings:156            return157158        # extrait = disponibilité (« DISPONIBLE AU 1-6-2026 ») quand publiée159        availability = ""160        excerpt = item.select_one(".elementor-widget-theme-post-excerpt "161                                  ".elementor-widget-container")162        if excerpt is not None:163            t = re.sub(r"\s+", " ", excerpt.get_text(" ", strip=True))164            if t:165                availability = t166167        images: list[str] = []168        thumb = item.select_one("img[src]")169        if thumb and thumb["src"].startswith("http"):170            images.append(thumb["src"])171172        m_type = _TYPE_RE.search(title)173        if m_type:174            unit_type = f"{m_type.group(1)}½"175        elif re.search(r"(?i)\bloft\b", title):176            unit_type = "Loft"177        else:178            unit_type = ""179180        m_addr = _ADDR_RE.search(title)181        address = f"{m_addr.group(1)}, Jonquière" if m_addr else ""182183        # fiche (cache : re-fetch seulement si le titre/extrait change)184        payload = self.detail(ext_id, f"{title}|{availability}",185                              lambda: self._fetch_detail(url))186187        price_label = payload.get("price_label", "")188        prices = [float(p.replace(" ", "").replace(" ", "").replace(",", "."))189                  for p in _PRICE_RE.findall(price_label)]190        prices = [p for p in prices if 100 <= p <= 20000]191192        for u in payload.get("images", []):193            if u not in images and len(images) < self.max_images:194                images.append(u)195196        listings[ext_id] = Listing(197            source=self.source_id,198            external_id=ext_id,199            url=url,200            title=title,201            address=address,202            sector="Jonquière",203            city="Saguenay",204            unit_type=normalize_unit_type(unit_type),205            price=min(prices) if prices else None,   # le plus bas (non meublé)206            price_label=price_label,207            availability=availability or payload.get("availability", ""),208            description=payload.get("description", ""),209            images=images,210        )211212    # -- fiche -------------------------------------------------------------------213    def _fetch_detail(self, url: str) -> dict:214        soup = BeautifulSoup(self.get(url).text, "html.parser")215        out: dict = {"price_label": "", "availability": "",216                     "description": "", "images": []}217218        # « Prix mensuel : » -> le heading suivant porte les tarifs219        headings = soup.select("h1, h2.elementor-heading-title")220        for i, h in enumerate(headings):221            t = re.sub(r"\s+", " ", h.get_text(" ", strip=True))222            if re.match(r"(?i)^prix\s+mensuel", t) and i + 1 < len(headings):223                out["price_label"] = re.sub(224                    r"\s+", " ", headings[i + 1].get_text(" ", strip=True))225            elif re.match(r"(?i)^disponible", t):226                # « Disponible : » suivi d'un heading date (« 1er juillet 2022 »)227                if t.rstrip(":").strip().lower() == "disponible" \228                        and i + 1 < len(headings):229                    nxt = re.sub(r"\s+", " ",230                                 headings[i + 1].get_text(" ", strip=True))231                    t = f"Disponible : {nxt}"232                out["availability"] = t233234        # paragraphes de la section « Informations »235        paras = [re.sub(r"\s+", " ", p.get_text(" ", strip=True))236                 for p in soup.select(".elementor-widget-text-editor p")]237        out["description"] = "\n".join(t for t in paras if len(t) >= 25)[:1600]238239        for img in soup.select("img[src*='/wp-content/uploads/']"):240            u = img["src"]241            if (u.startswith("http") and "logo" not in u.lower()242                    and not re.search(r"-\d+x\d+\.(?:jpe?g|png|webp)$", u)243                    and u not in out["images"]):244                out["images"].append(u)245                if len(out["images"]) >= self.max_images:246                    break247        return out248
Files main
Menu

Theme