# ----------------------------------------------------------------------------- # Immo-Ka — Agrégateur de maisons à vendre (province de Québec) # Auteur : Simon-Pierre Boucher — contact@spboucher.ai # connectors/royal_lepage.py : Royal LePage (royallepage.ca) — Québec # # Le portail rend ses résultats côté serveur, mais /fr/search/homes/{page}/ # sans géo renvoie le Canada entier. La recherche par ville EST filtrable : # /fr/search/homes/{page}/?search_str=...&prov_code=QC&city_name=...&lat=..& # lng=..&search_type=city renvoie 100 % de propriétés du Québec, classées par # proximité (46/page). Chaque recherche plafonne à ~1 250 résultats ; on # SHARD donc par points d'ancrage répartis dans la province et on dédoublonne # par numéro MLS (= n° Centris, dans l'URL /.../mls{no}/). Aucune dépendance # Firecrawl : requêtes directes. # ----------------------------------------------------------------------------- from __future__ import annotations import html as _html import os import re from .base import BaseConnector from . import _detailutil as du from ..normalize import parse_price from ..schema import PropertyListing BASE = "https://www.royallepage.ca/fr/search/homes" MAX_PAGES = 30 # une recherche plafonne à ~27 pages (~1250) # Le nom du BUREAU (« Royal LePage Humania »…) n'est pas sur la carte : il vient # de la fiche détail. Enrichissement plafonné + cache (agency se remplit au fil # des cycles). = affichage des Sources par sous-agence. DETAIL_LIMIT = int(os.environ.get("IMMOKA_RLP_DETAIL_LIMIT", "500")) _OFFICE_RE = re.compile(r'agent-info__brokerage".*?]*>\s*([^<,\n]+?)\s*(?:,|\n|)', re.S | re.I) # Points d'ancrage couvrant le Québec (nom, lat, lng). L'union des recherches # + dédoublonnage MLS couvre la province. ANCHORS = [ ("Montréal", 45.5089, -73.5542), ("Québec", 46.8139, -71.2080), ("Gatineau", 45.4765, -75.7013), ("Sherbrooke", 45.4040, -71.8929), ("Trois-Rivières", 46.3432, -72.5432), ("Saguenay", 48.4280, -71.0680), ("Laval", 45.6066, -73.7124), ("Longueuil", 45.5312, -73.5185), ("Drummondville", 45.8833, -72.4833), ("Saint-Jérôme", 45.7803, -74.0038), ("Granby", 45.4001, -72.7300), ("Rimouski", 48.4489, -68.5236), ("Rouyn-Noranda", 48.2360, -79.0230), ("Val-d'Or", 48.0975, -77.7972), ("Gaspé", 48.8330, -64.4870), ("Sept-Îles", 50.2001, -66.3821), ("Baie-Comeau", 49.2166, -68.1487), ("Joliette", 46.0167, -73.4500), ("Saint-Hyacinthe", 45.6300, -72.9569), ("Sorel-Tracy", 46.0500, -73.1200), ("Victoriaville", 46.0533, -71.9667), ("Mont-Laurier", 46.5500, -75.5000), ("Alma", 48.5500, -71.6500), ("Matane", 48.8500, -67.5300), ("Saint-Sauveur", 45.8939, -74.2051), ("Baie-Saint-Paul", 47.4400, -70.5000), ("Salaberry-de-Valleyfield", 45.2500, -74.1300), ("Thetford Mines", 46.1000, -71.3000), ] _CARD_RE = re.compile(r'card--listing-card js-listing js-property-details(.*?)' r'(?=card--listing-card js-listing js-property-details||$)', re.S) _URL_RE = re.compile(r'/fr/property/quebec/[^"\']+?/mls[a-z0-9]+/', re.I) _MLS_RE = re.compile(r'/mls([a-z0-9]+)/', re.I) _KEY_RE = re.compile(r'data-rlp-key="(-?\d+\.\d+)\.(-?\d+\.\d+)"') _PHOTO_RE = re.compile(r'(//rlp\.jumplisting\.com/photos/[^"\']+)') _CAC_RE = re.compile(r'(\d+)\s*CAC', re.I) _SDB_RE = re.compile(r'(\d+)(?:\+\d+)?\s*SDB', re.I) _PRICE_RE = re.compile(r'([\d\s ]{4,})\s*\|?\s*\$') _TYPE_RE = re.compile(r'\|\s*(Maison|Condo|Appartement|Duplex|Triplex|Plex|Terrain|' r'Chalet|Fermette|Ferme|Loft|Terre|Maison de ville|Jumelé|' r'Quadruplex|Quintuplex|Commercial)\s*\|', re.I) class RoyalLepageConnector(BaseConnector): source_id = "royal_lepage" request_delay = 0.4 def fetch(self) -> list[PropertyListing]: by_id: dict[str, PropertyListing] = {} for name, lat, lng in ANCHORS: self._search_anchor(name, lat, lng, by_id) listings = list(by_id.values()) # bureau (agency) via la fiche détail — plafonné, cache accumulé du.enrich(self, listings, DETAIL_LIMIT, _parse_rlp_office, key="office1") for lst in listings: office = lst.details.pop("__agency", "") if office: lst.agency = office return listings def _search_anchor(self, name: str, lat: float, lng: float, out: dict) -> None: empty_streak = 0 for page in range(1, MAX_PAGES + 1): params = { "search_str": f"{name}, QC", "prov_code": "QC", "city_name": name, "lat": lat, "lng": lng, "search_type": "city", } try: html = self.get(f"{BASE}/{page}/", params=params, headers={"X-Requested-With": "XMLHttpRequest"}).text except Exception: break new = 0 for lst in self._parse_cards(html): if lst.external_id not in out: out[lst.external_id] = lst new += 1 if new == 0: empty_streak += 1 if empty_streak >= 2: # cap serveur atteint (page répétée) break else: empty_streak = 0 def _parse_cards(self, html: str) -> list[PropertyListing]: out = [] for seg in _CARD_RE.findall(html): murl = _URL_RE.search(seg) if not murl: continue url = "https://www.royallepage.ca" + murl.group(0) mls = _MLS_RE.search(url) ext = mls.group(1) if mls else url # /fr/property/quebec/{ville}/{adresse}/{id}/mls{no}/ parts = murl.group(0).strip("/").split("/") city = parts[3].replace("-", " ").title() if len(parts) > 3 else "" address = parts[4].replace("-", " ").title() if len(parts) > 4 else "" flat = _html.unescape(re.sub(r"<[^>]+>", " | ", seg)) flat = re.sub(r"(\s*\|\s*)+", " | ", re.sub(r"\s+", " ", flat)) beds = _CAC_RE.search(flat) baths = _SDB_RE.search(flat) price = _PRICE_RE.search(flat) typ = _TYPE_RE.search(flat) key = _KEY_RE.search(seg) photo = _PHOTO_RE.search(seg) images = [] if photo: images = ["https:" + photo.group(1).replace("_0_med", "_0_lg")] out.append(PropertyListing( source=self.source_id, external_id=str(ext), url=url, title=address, address=address, city=city, region="Québec", property_type=(typ.group(1) if typ else ""), price=(parse_price(price.group(1)) if price else None), price_label=(price.group(0).strip() if price else ""), bedrooms=int(beds.group(1)) if beds else None, bathrooms=int(baths.group(1)) if baths else None, mls=(mls.group(1) if mls else ""), images=images, lat=float(key.group(1)) if key else None, lng=float(key.group(2)) if key else None, broker_name="Royal LePage", )) return out def _parse_rlp_office(html: str) -> dict: """Extrait le bureau/brokerage de la fiche détail Royal LePage.""" m = _OFFICE_RE.search(html) if not m: return {} office = _html.unescape(m.group(1)).strip() return {"details": {"__agency": office}} if office else {}