SPB Git

Repository Public

net.py 6.0 KB 150 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/net.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/net.py (ka-apartments-com)90# Desc:   Fetcher Bright Data Web Unlocker — apartments.com est verrouillé par91#         Akamai (curl_cffi/Scrapfly/Oxylabs → 403) ; seul le Web Unlocker92#         passe. Simple POST https://api.brightdata.com/request qui renvoie le93#         HTML brut de la page débloquée. httpx async + sémaphore + retries à94#         backoff exponentiel.95# ==============================================================================96from __future__ import annotations9798import asyncio99import random100101import httpx102103from apify import Actor104105API = "https://api.brightdata.com/request"106107108def _backoff(attempt: int) -> float:109    return min(1.5 * (2 ** attempt), 15.0) + random.uniform(0.0, 1.0)110111112class BrightData:113    """GET d'une page via le Web Unlocker Bright Data (déblocage géré)."""114115    def __init__(self, token: str, zone: str, concurrency: int = 4,116                 delay: float = 0.0) -> None:117        self._headers = {"Authorization": f"Bearer {token}",118                         "Content-Type": "application/json"}119        self._zone = zone120        self._sem = asyncio.Semaphore(max(1, concurrency))121        self._delay = max(0.0, delay)122        self._client = httpx.AsyncClient(timeout=120.0)123124    async def close(self) -> None:125        await self._client.aclose()126127    async def get(self, url: str, retries: int = 3) -> str | None:128        """HTML de la page, ou None si le déblocage échoue après retries."""129        body = {"zone": self._zone, "url": url,130                "format": "raw", "country": "ca"}131        async with self._sem:132            for attempt in range(retries):133                try:134                    resp = await self._client.post(135                        API, headers=self._headers, json=body)136                    if resp.status_code == 200 and resp.text.strip():137                        if self._delay:138                            await asyncio.sleep(self._delay)139                        return resp.text140                    Actor.log.warning(141                        f"Bright Data {resp.status_code} {url} — "142                        f"{resp.text[:120]!r} (tentative {attempt + 1})")143                except httpx.HTTPError as exc:144                    Actor.log.warning(145                        f"Bright Data réseau {url} : {exc} "146                        f"(tentative {attempt + 1})")147                if attempt < retries - 1:148                    await asyncio.sleep(_backoff(attempt))149        return None150
Files main
Menu

Theme