SPB Git

Repository Public

habitations_jeanne.py 8.4 KB 205 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/habitations_jeanne.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/habitations_jeanne.py : connecteur Les Habitations Jeanne inc.91#   (leshabitationsjeanne.com — Baie-Comeau, Côte-Nord, 200+ appartements).92#   Site Wix rendu serveur : la page /appartements-meubles présente des cartes93#   d'unités réelles (adresse civique, numéro d'appartement « App. 12 », type94#   « appartement 5 ½ », galerie de photos Wix) — location mensuelle, meublé.95#   La page /appartements-non-meubles est une vitrine (texte + adresses du parc,96#   aucune carte d'unité) : elle est parcourue avec le même parseur et97#   contribuera des annonces si des cartes y apparaissent un jour.98#   Aucun prix ni disponibilité publiés (granularité vitrine assumée, comme99#   immeubles_guillot) ; les photos et types sont réels, unité par unité.100#   robots.txt Wix ouvert (Disallow *?lightbox= seulement), sitemap XML.101# -----------------------------------------------------------------------------102from __future__ import annotations103104import re105106from bs4 import BeautifulSoup107108from ..schema import Listing, normalize_unit_type, strip_accents109from .base import BaseConnector110111BASE = "https://www.leshabitationsjeanne.com"112# (url, meublé) — les deux pages du site ; seuls les meublés ont des cartes113PAGES = [114    (f"{BASE}/appartements-meubles", True),115    (f"{BASE}/appartements-non-meubles", False),116]117118_APP_RE = re.compile(r"App\.\s*(\d+[A-Za-z]?)", re.I)119_TYPE_RE = re.compile(r"([1-9])\s*(?:½|1/2)")120# adresse civique : numéro puis nom de voie (« 3, avenue du Père-Arnaud »,121# « 20 Roberval ») — le vrai filtre est l'appariement avec le bloc « App. » suivant122_ADDR_RE = re.compile(r"^\d+[A-Za-z]?,?\s+\D")123124125def _slug(text: str) -> str:126    """Texte -> slug stable ascii (« 3, avenue du Père-Arnaud » -> « 3-avenue-du-pere-arnaud »)."""127    s = strip_accents(text.lower())128    return re.sub(r"-{2,}", "-", re.sub(r"[^a-z0-9]+", "-", s)).strip("-")129130131def _full_size(url: str) -> str:132    """URL wixstatic redimensionnée -> média pleine taille (coupe au /v1/)."""133    return url.split("/v1/")[0] if "/v1/" in url else url134135136class HabitationsJeanneConnector(BaseConnector):137    source_id = "habitations_jeanne"138    request_delay = 0.6139140    def fetch(self) -> list[Listing]:141        listings: dict[str, Listing] = {}142        for url, furnished in PAGES:143            try:144                html = self.get(url).text145            except Exception:146                continue147            self._parse_page(html, url, furnished, listings)148        return list(listings.values())149150    # -- cartes d'unités (Wix SSR) --------------------------------------------------151    def _parse_page(self, html: str, page_url: str, furnished: bool,152                    listings: dict[str, Listing]) -> None:153        soup = BeautifulSoup(html, "html.parser")154        # séquence des blocs de texte riche : une adresse civique suivie du bloc155        # « App. N / appartement X ½ » = une carte d'unité156        blocks = soup.select('div[data-testid="richTextElement"]')157        for i, blk in enumerate(blocks):158            addr = re.sub(r"\s+", " ", blk.get_text(" ", strip=True))159            if not _ADDR_RE.match(addr) or _APP_RE.search(addr):160                continue161            if i + 1 >= len(blocks):162                continue163            info = re.sub(r"\s+", " ", blocks[i + 1].get_text(" ", strip=True))164            m_app = _APP_RE.search(info)165            if not m_app:166                continue167            app_no = m_app.group(1)168169            m_type = _TYPE_RE.search(info)170            unit_label = f"{m_type.group(1)} ½" if m_type else ""171172            ext_id = f"{_slug(addr)}--app-{app_no.lower()}"173            if not ext_id or ext_id in listings:174                continue175176            # galerie : images wixstatic de la carte (ancêtre contenant adresse + App.)177            images: list[str] = []178            card = blk179            while card is not None and "App." not in card.get_text():180                card = card.parent181            if card is not None:182                for im in card.select("img[src]"):183                    u = _full_size(im["src"])184                    if u.startswith("https://static.wixstatic.com") and u not in images:185                        images.append(u)186187            title = f"{addr} — App. {app_no}"188            if unit_label:189                title += f" ({unit_label}{' meublé' if furnished else ''})"190191            listings[ext_id] = Listing(192                source=self.source_id,193                external_id=ext_id,194                url=page_url,195                title=title,196                address=addr,197                city="Baie-Comeau",             # tout le parc affiché est à Baie-Comeau198                unit_type=normalize_unit_type(unit_label),199                price=None,                      # jamais publié sur le site200                price_label="",201                availability="",202                furnished=furnished,203                images=images[:15],204            )205
Files main
Menu

Theme