SPB Git

Repository Public

main.py 14.5 KB 357 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : actors/ka-apartments-com/src/main.py10# Module           : actors11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-2213# Last Modified    : 2026-08-2214#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# Author: Simon-Pierre Boucher <contact@spboucher.ai>89# File:   src/main.py (ka-apartments-com)90# Desc:   Apartments.com — logements à louer, province de Québec.91#         Phase 1 : pagination des pages de recherche (/qc/ = toute la92#         province, HTML server-rendered ; arrêt quand le <title> ne porte93#         plus « - Page N », le site retombant silencieusement sur la page 1).94#         Phase 2 : fiches détail en français (/fr/<slug>/<id>/) : GPS,95#         description, plans d'unités (pricingGridItem), commodités, galerie.96#         Items poussés : kind="listing" (placard) et kind="detail".97# ==============================================================================98from __future__ import annotations99100import asyncio101import html as htmllib102import re103104from apify import Actor105106from .net import BrightData107108# --- recherche (placards) -----------------------------------------------------109110_ARTICLE_RX = re.compile(111    r"<article\b(?P<attrs>[^>]*\bdata-listingid=\"[^\"]+\"[^>]*)>"112    r"(?P<body>.*?)</article>", re.S)113_ATTR_RX = re.compile(r"data-(listingid|url|streetaddress)=\"([^\"]*)\"")114_TITLE_TAG_RX = re.compile(r"<title>([^<]*)</title>")115_PLACARD_TITLE_RX = re.compile(r"js-placardTitle[^\"]*\"[^>]*>([^<]+)<")116_ADDRESS_RX = re.compile(r"property-address[^\"]*\"[^>]*>([^<]+)<")117_BED_RENT_RX = re.compile(118    r"bedTextBox\">([^<]*)<.{0,400}?priceTextBox\">\s*<span[^>]*>([^<]*)<",119    re.S)120_IMG_COUNT_RX = re.compile(r"js-spnImgCount\">(\d+)")121_PHONE_RX = re.compile(r"phone-data=\"(\d{7,15})\"")122_AMENITIES_BLOCK_RX = re.compile(123    r"property-amenities\"[^>]*>(.*?)</p>", re.S)124_SPAN_RX = re.compile(r"<span[^>]*>([^<]+)</span>")125_IMG_RX = re.compile(r"https://images1\.apartments\.com/i2/[^\"'\s?]+")126_QC_SLUG_RX = re.compile(r"apartments\.com/[^\"]*-qc[-/]")127128129def _clean(text: str) -> str:130    return re.sub(r"\s+", " ", htmllib.unescape(text or "")).strip()131132133def parse_search(page_html: str) -> list[dict]:134    """Placards d'une page de recherche → dicts (propriétés QC seulement)."""135    out: list[dict] = []136    for m in _ARTICLE_RX.finditer(page_html):137        attrs = dict(_ATTR_RX.findall(m.group("attrs")))138        pid, url = attrs.get("listingid", ""), attrs.get("url", "")139        if not pid or not url:140            continue141        body = m.group("body")142        title_m = _PLACARD_TITLE_RX.search(body)143        addr_m = _ADDRESS_RX.search(body)144        title = _clean(title_m.group(1)) if title_m else ""145        address = _clean(addr_m.group(1)) if addr_m else ""146        if not address and ", QC" in title:147            address = title  # gabarit silverpropres : adresse dans le titre148        # nearby hors-Québec glissé en bas de page → on filtre149        if ", QC" not in address and not _QC_SLUG_RX.search(url):150            continue151        rents = [{"beds": _clean(b), "price": _clean(p)}152                 for b, p in _BED_RENT_RX.findall(body)]153        img_count_m = _IMG_COUNT_RX.search(body)154        phone_m = _PHONE_RX.search(body)155        amen_m = _AMENITIES_BLOCK_RX.search(body)156        amenities = [_clean(s) for s in _SPAN_RX.findall(amen_m.group(1))] \157            if amen_m else []158        img_m = _IMG_RX.search(body)159        out.append({160            "id": pid,161            "url": url,162            "title": title,163            "address": address,164            "street": _clean(attrs.get("streetaddress", "")),165            "rents": rents,166            "img_count": int(img_count_m.group(1)) if img_count_m else 0,167            "phone": phone_m.group(1) if phone_m else "",168            "amenities": [a for a in amenities if a],169            "image": img_m.group(0) if img_m else "",170        })171    return out172173174def page_title(page_html: str) -> str:175    m = _TITLE_TAG_RX.search(page_html)176    return _clean(m.group(1)) if m else ""177178179# --- fiche détail (version française) ------------------------------------------180181_META_LAT_RX = re.compile(182    r"<meta property=\"place:location:latitude\" content=\"([^\"]+)\"")183_META_LNG_RX = re.compile(184    r"<meta property=\"place:location:longitude\" content=\"([^\"]+)\"")185_PROP_NAME_RX = re.compile(r"id=\"propertyName\"[^>]*>([^<]+)")186_ADDR_BLOCK_RX = re.compile(187    r"delivery-address\"><span>([^<]+)</span>.*?<span>([^<]+)</span>,\s*"188    r"<span class=\"stateZipContainer\">\s*<span>([^<]+)</span>\s*"189    r"<span>([^<]*)</span>", re.S)190_DESC_SECTION_RX = re.compile(191    r"<section[^>]*id=\"descriptionSection\"[^>]*>(.*?)</section>", re.S)192_MODEL_WRAPPER_RX = re.compile(193    r"priceGridModelWrapper[^\"]*\"\s*data-rentalkey=\"([^\"]*)\"(.*?)"194    r"(?=priceGridModelWrapper|$)", re.S)195_MODEL_NAME_RX = re.compile(r"modelName\">([^<]+)<")196_RENT_LABEL_RX = re.compile(r"rentLabel\">\s*([^<]+)")197_DETAILS_WRAPPER_RX = re.compile(198    r"detailsTextWrapper\">(.*?)</span>\s*</span>", re.S)199_AVAIL_RX = re.compile(r"availabilityInfo\">([^<]+)<")200_BEDS_BATHS_RX = re.compile(r"data-beds=\"([^\"]*)\"\s*data-baths=\"([^\"]*)\"")201_SPEC_INFO_RX = re.compile(r"specInfo\">\s*<span>([^<]+)</span>")202_TAG_RX = re.compile(r"<[^>]+>")203204205def _to_float(text: str) -> float | None:206    try:207        return float(text.strip())208    except (TypeError, ValueError):209        return None210211212def parse_detail(page_html: str) -> dict:213    out: dict = {}214    name_m = _PROP_NAME_RX.search(page_html)215    if name_m:216        out["name"] = _clean(name_m.group(1))217    addr_m = _ADDR_BLOCK_RX.search(page_html)218    if addr_m:219        out["street"] = _clean(addr_m.group(1))220        out["city"] = _clean(addr_m.group(2))221        out["state"] = _clean(addr_m.group(3))222        out["zip"] = _clean(addr_m.group(4))223    lat_m, lng_m = _META_LAT_RX.search(page_html), _META_LNG_RX.search(page_html)224    if lat_m and lng_m:225        out["lat"] = _to_float(lat_m.group(1))226        out["lng"] = _to_float(lng_m.group(1))227    desc_m = _DESC_SECTION_RX.search(page_html)228    if desc_m:229        lines = [_clean(t) for t in230                 _TAG_RX.sub("\n", desc_m.group(1)).split("\n")]231        lines = [t for t in lines if t232                 and not t.lower().startswith(("à propos", "about"))]233        if lines:234            out["description"] = "\n\n".join(dict.fromkeys(lines))235    plans: list[dict] = []236    for key, body in _MODEL_WRAPPER_RX.findall(page_html):237        plan: dict = {"key": key}238        nm = _MODEL_NAME_RX.search(body)239        if nm:240            plan["name"] = _clean(nm.group(1))241        rl = _RENT_LABEL_RX.search(body)242        if rl:243            plan["rent"] = _clean(rl.group(1))244        dw = _DETAILS_WRAPPER_RX.search(body)245        if dw:246            plan["details"] = [_clean(s) for s in247                               _SPAN_RX.findall(dw.group(1) + "</span>")]248        bb = _BEDS_BATHS_RX.search(body)249        if bb:250            plan["beds"] = _to_float(bb.group(1))251            plan["baths"] = _to_float(bb.group(2))252        av = _AVAIL_RX.search(body)253        if av:254            plan["availability"] = _clean(av.group(1))255        if plan.get("name") or plan.get("rent"):256            # la grille est présente deux fois dans la page (desktop/mobile)257            if not any(p.get("key") == plan.get("key")258                       and p.get("name") == plan.get("name")259                       and p.get("rent") == plan.get("rent") for p in plans):260                plans.append(plan)261    if plans:262        out["plans"] = plans263    amenities = [_clean(s) for s in _SPEC_INFO_RX.findall(page_html)]264    if amenities:265        out["amenities"] = list(dict.fromkeys(a for a in amenities if a))266    images = list(dict.fromkeys(267        u for u in _IMG_RX.findall(page_html) if "-logo" not in u))268    if images:269        out["images"] = images270    return out271272273def fr_url(url: str) -> str:274    if "apartments.com/fr/" in url:275        return url276    return url.replace("www.apartments.com/", "www.apartments.com/fr/", 1)277278279# --- orchestration --------------------------------------------------------------280281async def _crawl_search(bd: BrightData, base: str, max_pages: int,282                        props: dict[str, dict]) -> None:283    base = base if base.endswith("/") else base + "/"284    for page in range(1, max_pages + 1):285        url = base if page == 1 else f"{base}{page}/"286        page_html = await bd.get(url)287        if page_html is None:288            Actor.log.warning(f"recherche : échec fetch {url}, arrêt")289            break290        if page > 1 and f"- Page {page}" not in page_title(page_html):291            Actor.log.info(f"recherche : fin de pagination à la page {page} "292                           f"({base})")293            break294        placards = parse_search(page_html)295        if not placards:296            Actor.log.info(f"recherche : page {page} vide ({base})")297            break298        fresh = [p for p in placards if p["id"] not in props]299        for p in fresh:300            props[p["id"]] = p301            await Actor.push_data({"kind": "listing", **p})302        Actor.log.info(f"recherche p.{page} : {len(placards)} placards, "303                       f"{len(fresh)} nouveaux ({base})")304305306async def _fetch_detail(bd: BrightData, pid: str, url: str) -> None:307    page_html = await bd.get(fr_url(url))308    if page_html is None:309        Actor.log.warning(f"détail {pid} : échec fetch")310        return311    detail = parse_detail(page_html)312    if not detail:313        Actor.log.warning(f"détail {pid} : page sans données")314        return315    await Actor.push_data({"kind": "detail", "id": pid, "url": url, **detail})316317318async def main() -> None:319    async with Actor:320        inp = await Actor.get_input() or {}321        token = (inp.get("brightdataToken") or "").strip()322        if not token:323            raise ValueError("brightdataToken requis (Web Unlocker)")324        bd = BrightData(325            token=token,326            zone=(inp.get("brightdataZone") or "web_unlocker1").strip(),327            concurrency=int(inp.get("concurrency") or 4),328            delay=float(inp.get("requestDelay") or 0))329        try:330            search_urls = [u.strip() for u in331                           (inp.get("searchUrls")332                            or ["https://www.apartments.com/qc/"])333                           if u and u.strip()]334            max_pages = int(inp.get("maxPages") or 25)335            props: dict[str, dict] = {}336            for base in search_urls:337                await _crawl_search(bd, base, max_pages, props)338            Actor.log.info(f"recherche terminée : {len(props)} propriétés")339340            if not inp.get("getDetails", True):341                return342            skip = set(inp.get("skipDetailIds") or [])343            targets: list[tuple[str, str]] = [344                (pid, p["url"]) for pid, p in props.items() if pid not in skip]345            for enc in inp.get("extraDetailIds") or []:346                pid, _, url = enc.partition("|")347                if pid and url and pid not in props and pid not in skip:348                    targets.append((pid, url))349            max_details = int(inp.get("maxDetails") or 0)350            if max_details >= 0:351                targets = targets[:max_details]352            Actor.log.info(f"détails : {len(targets)} fiches à visiter")353            await asyncio.gather(354                *(_fetch_detail(bd, pid, url) for pid, url in targets))355        finally:356            await bd.close()357
Files main
Menu

Theme