SPB Git

Repository Public

gparadis.py 10.9 KB 270 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/connectors/gparadis.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/gparadis.py : connecteur GParadis (gparadis.com)91#   Secteurs : Montcalm, St-Sauveur, St-Roch, Limoilou, Vieux-Québec,92#   Ste-Foy, Duberger, Lévis. Les pages de secteurs (WordPress) décrivent93#   chaque immeuble (bloc wp-block-group + h5) avec adresses, disponibilités94#   (« 4 1/2 disponible MAINTENANT »), commodités et galeries de photos.95#   Une annonce par immeuble ayant des unités disponibles.96# -----------------------------------------------------------------------------97from __future__ import annotations9899import re100101from bs4 import BeautifulSoup102103from ..schema import Listing, infer_city, normalize_unit_type, strip_accents104from .base import BaseConnector105106BASE = "https://gparadis.com"107SECTOR_PAGES = {108    "montcalm": "Montcalm",109    "saint-sauveur": "Saint-Sauveur",110    "limoilou": "Limoilou",111    "levis": "Lévis",112    "vieux-quebec": "Vieux-Québec",113    "ste-foy": "Ste-Foy",114    "duberger": "Duberger",115    "saint-roch": "Saint-Roch",116}117BAD_IMG_RE = re.compile(r"logo|icon|favicon|cropped-|gparadis-69fb", re.I)118119# Contact « Pour louer » du pied de page (numéro dédié aux locations ;120# le Vieux-Québec a son propre numéro)121PHONE_VQ_RE = re.compile(122    r"Pour louer dans Vieux-Qu[ée]bec\s*:?\s*(\d{3})\s*-?\s*(\d{3})\s*-?\s*(\d{4})", re.I)123PHONE_RE = re.compile(124    r"Pour louer\s*:?\s*(\d{3})\s*-?\s*(\d{3})\s*-?\s*(\d{4})", re.I)125EMAIL_RE = re.compile(r"\b[\w.+-]+@gparadis\.com\b", re.I)126127128def _slugify(s: str) -> str:129    s = strip_accents(s.lower())130    return re.sub(r"[^a-z0-9]+", "-", s).strip("-")[:60]131132133class GParadisConnector(BaseConnector):134    source_id = "gparadis"135    request_delay = 0.6136137    def fetch(self) -> list[Listing]:138        listings: dict[str, Listing] = {}139        for slug, sector in SECTOR_PAGES.items():140            url = f"{BASE}/{slug}/"141            try:142                html = self.get(url).text143            except Exception:144                continue145            try:146                self._parse_sector(html, url, sector, listings)147            except Exception:148                continue149        return list(listings.values())150151    def _parse_sector(self, html: str, url: str, sector: str,152                      listings: dict[str, Listing]) -> None:153        soup = BeautifulSoup(html, "html.parser")154        seen_groups: set[int] = set()155156        # contact « Pour louer » du pied de page (structuré à la source) —157        # le Vieux-Québec a son numéro dédié158        page_text = re.sub(r"\s+", " ", soup.get_text(" ", strip=True))159        contact: dict = {}160        pm = (PHONE_VQ_RE.search(page_text)161              if "vieux" in strip_accents(sector.lower()) else None) or \162            PHONE_RE.search(page_text)163        if pm:164            contact["phone"] = f"{pm.group(1)}-{pm.group(2)}-{pm.group(3)}"165        em = EMAIL_RE.search(page_text)166        if em:167            contact["email"] = em.group(0).lower()168169        for h in soup.select("h5.wp-block-heading"):170            # le bloc « carte d'immeuble » = plus proche ancêtre wp-block-group171            # (le nom et l'adresse peuvent être dans des h5 distincts du bloc)172            group = h.find_parent("div", class_="wp-block-group")173            if group is None or id(group) in seen_groups:174                continue175            seen_groups.add(id(group))176            headings = group.find_all("h5", class_="wp-block-heading")177178            text = re.sub(r"\s+", " ", group.get_text(" ", strip=True))179            # Immeubles complets : rien à annoncer180            if re.search(r"\bComplet\b", text) and \181                    not re.search(r"disponible", text, re.I):182                continue183            # Disponibilités : « 5 1/2 disponible MAINTENANT », « ... le 1er184            # juillet », « lofts disponibles le 1 er juillet »185            avail_parts = re.findall(186                r"((?:\d\s*1/2|\d\s*½|Studios?|Lofts?)"187                r"(?:\s*(?:,|et)\s*(?:\d\s*1/2|\d\s*½))*"188                r"\s*disponibles?\s*(?:MAINTENANT|le\s*1\s*er\s*[a-zû]+|"189                r"d[èe]s\s+maintenant)?)", text, re.I)190            if not avail_parts:191                continue  # aucune unité disponible décrite192            availability = " ; ".join(p.strip() for p in avail_parts)[:200]193194            # nom + adresse(s) : lignes des h5 du bloc (séparées par <br>)195            lines: list[str] = []196            for hh in headings:197                for l in re.split(r"<br\s*/?>", hh.decode_contents()):198                    l = re.sub(r"<[^>]+>", "", l)199                    l = (l.replace("&#8211;", "–").replace("&amp;", "&")200                         .replace("&#8217;", "'").strip())201                    if l:202                        lines.append(l)203            name = ""204            addresses = []205            for l in lines:206                if re.match(r"^\d", l):207                    addresses.append(l)208                elif not name:209                    name = l210            address = addresses[0] if addresses else ""211            title = name or address212            if not title:213                continue214215            # type d'unité : premier type disponible mentionné216            tm = re.search(r"(\d)\s*(?:1/2|½)", availability)217            if tm:218                unit_type = f"{tm.group(1)}½"219            elif re.search(r"lofts?", availability, re.I):220                unit_type = "Loft"221            elif re.search(r"studios?", availability, re.I):222                unit_type = "Studio"223            else:224                unit_type = ""225226            # commodités227            amenities = [li.get_text(" ", strip=True)228                         for li in group.select("li")229                         if li.get_text(strip=True)][:15]230231            # images de la galerie de l'immeuble232            images = []233            for im in group.select("img"):234                u = im.get("data-orig-file") or im.get("src") or ""235                u = u.split("?")[0]236                if u and re.search(r"\.(?:jpe?g|png|webp)$", u, re.I) \237                        and not BAD_IMG_RE.search(u):238                    images.append(u)239            images = list(dict.fromkeys(images))[:25]240            if not images and len(soup.select("h5.wp-block-heading")) == 1:241                # page à immeuble unique : galerie au niveau de la page242                for im in soup.select("img"):243                    u = (im.get("data-orig-file") or im.get("src") or "")244                    u = u.split("?")[0]245                    if u and re.search(r"\.(?:jpe?g|png|webp)$", u, re.I) \246                            and not BAD_IMG_RE.search(u):247                        images.append(u)248                images = list(dict.fromkeys(images))[:25]249250            ext_id = f"{_slugify(sector)}-{_slugify(title if not addresses else f'{title}-{address}')}"251            if ext_id in listings:252                continue253            listings[ext_id] = Listing(254                source=self.source_id,255                external_id=ext_id,256                url=url,257                title=title,258                address=address,259                sector=sector,260                city=infer_city(sector),261                unit_type=normalize_unit_type(unit_type),262                price=None,          # GParadis n'affiche pas les prix263                price_label="",264                availability=availability,265                description=text[:600],266                amenities=amenities,267                details={"contact": dict(contact)} if contact else {},268                images=images,269            )270
Files main
Menu

Theme