Spaces:
Runtime error
Runtime error
Update app.py
Browse files19 unmodified lines202122232425269 unmodified lines363738394041424344454647484950515210 unmodified lines636465666768691 unmodified line717273747576774 unmodified lines82838485868788899091929394959697989910010110210310410516 unmodified lines12212312412512612712830 unmodified lines15916016116216316416516616716816917017117217317417519 unmodified linessubprocess.run(["pip", "install", "fake-useragent"], check=True)from fake_useragent import UserAgent# --- 1. GENERADOR DE URLS (CORREGIDO CON RUTA COMPLETA) ---def construir_urls_final(zona, ciudad, tipo, hab, ban, park, antiguedad):mapa_ant = {"Menos de 1 año": "de-0-a-1-anos",9 unmodified linesz_slug = zona.lower().strip().replace(" ", "-")c_slug = ciudad.lower().strip().replace(" ", "-")# URL FINCA RAÍZ: /arriendo/barrio/ciudad/filtrosurl_fr = f"https://www.fincaraiz.com.co/arriendo/{z_slug}/{c_slug}/{int(hab)}-o-mas-habitaciones/{int(ban)}-o-mas-banos/{slug_park}/{slug_ant}"# URL METROCUADRADOurl_mc = f"https://www.metrocuadrado.com/{tipo.lower()}-casa-oficina/arriendo/{c_slug}/{int(ban)}-banos-{int(hab)}-habitaciones/?search=form"return url_fr, url_mc# --- 2. EXTRACTOR DE PRECIO (REGEX) ---def extraer_precio_regex(texto):# Detecta $ 1.500.000 o $1500000patron = r'\$\s?(\d{1,3}(?:[.,]\d{3})*)'coincidencias = re.findall(patron, texto)if coincidencias:10 unmodified linesua = UserAgent()with sync_playwright() as p:# Lanzamos navegador con perfil de evasiónbrowser = p.chromium.launch(headless=True,args=[1 unmodified line'--no-sandbox','--disable-infobars','--window-position=0,0',f'--user-agent={ua.random}' # Identidad aleatoria])context = browser.new_context(viewport={'width': 1366, 'height': 768})4 unmodified lineslog_visible += "🔄 Escaneando Finca Raíz...\n"page.goto(url_fr, wait_until="domcontentloaded", timeout=60000)# Movimiento humanopage.mouse.move(random.randint(100, 500), random.randint(100, 500))for _ in range(4):page.mouse.wheel(0, 1000)time.sleep(1.5) # Espera para cargar elementos dinámicos# Buscamos enlaces (Links <a>)elementos = page.query_selector_all("a")cont_fr = 0# Extraemos hasta 15 para tener margen de descartefor el in elementos:if cont_fr >= 15: breaktxt = el.inner_text()if "$" in txt:precio = extraer_precio_regex(txt)if precio > 600000: # Filtro anti-ruido (precios muy bajos)href = el.get_attribute("href")full_url = f"https://www.fincaraiz.com.co{href}" if href and href.startswith("/") else href16 unmodified lineslog_visible += "🔄 Escaneando Metrocuadrado...\n"page.goto(url_mc, wait_until="domcontentloaded", timeout=60000)for _ in range(5): # Un poco más de scroll en MCpage.mouse.wheel(0, 1000)time.sleep(1.5)30 unmodified linesif not resultados:return f"{log_visible}\n❌ NO SE ENCONTRARON DATOS VÁLIDOS.", None, None, "---"# --- LIMPIEZA Y SELECCIÓN DE LOS 6 MEJORES ---df_crudo = pd.DataFrame(resultados)# 1. Eliminar duplicados exactos de URLdf_limpio = df_crudo.drop_duplicates(subset=['URL'])# 2. Seleccionar top 6 por portaldf_fr = df_limpio[df_limpio['Portal'] == 'Finca Raiz'].head(6)df_mc = df_limpio[df_limpio['Portal'] == 'Metrocuadrado'].head(6)# 3. Combinardf_final = pd.concat([df_fr, df_mc]).reset_index(drop=True)log_visible += f"\n✨ PROCESADO FINAL: {len(df_final)} inmuebles únicos seleccionados para el reporte."19 unmodified lines202122232425269 unmodified lines3637383940414243444546474849505110 unmodified lines6263646566671 unmodified line697071727374754 unmodified lines808182838485868788899091929394959697989910016 unmodified lines11711811912012112212330 unmodified lines15415515615715815916016116216316416516619 unmodified linessubprocess.run(["pip", "install", "fake-useragent"], check=True)from fake_useragent import UserAgent# --- 1. GENERADOR DE URLS (CORREGIDO MC Y FR) ---def construir_urls_final(zona, ciudad, tipo, hab, ban, park, antiguedad):mapa_ant = {"Menos de 1 año": "de-0-a-1-anos",9 unmodified linesz_slug = zona.lower().strip().replace(" ", "-")c_slug = ciudad.lower().strip().replace(" ", "-")# URL FINCA RAÍZurl_fr = f"https://www.fincaraiz.com.co/arriendo/{z_slug}/{c_slug}/{int(hab)}-o-mas-habitaciones/{int(ban)}-o-mas-banos/{slug_park}/{slug_ant}"# URL METROCUADRADO CORREGIDA (Se añade {z_slug})url_mc = f"https://www.metrocuadrado.com/{tipo.lower()}-casa-oficina/arriendo/{c_slug}/{z_slug}/{int(ban)}-banos-{int(hab)}-habitaciones/?search=form"return url_fr, url_mc# --- 2. EXTRACTOR DE PRECIO (REGEX) ---def extraer_precio_regex(texto):patron = r'\$\s?(\d{1,3}(?:[.,]\d{3})*)'coincidencias = re.findall(patron, texto)if coincidencias:10 unmodified linesua = UserAgent()with sync_playwright() as p:browser = p.chromium.launch(headless=True,args=[1 unmodified line'--no-sandbox','--disable-infobars','--window-position=0,0',f'--user-agent={ua.random}'])context = browser.new_context(viewport={'width': 1366, 'height': 768})4 unmodified lineslog_visible += "🔄 Escaneando Finca Raíz...\n"page.goto(url_fr, wait_until="domcontentloaded", timeout=60000)page.mouse.move(random.randint(100, 500), random.randint(100, 500))for _ in range(4):page.mouse.wheel(0, 1000)time.sleep(1.5)elementos = page.query_selector_all("a")cont_fr = 0for el in elementos:if cont_fr >= 15: breaktxt = el.inner_text()if "$" in txt:precio = extraer_precio_regex(txt)if precio > 600000:href = el.get_attribute("href")full_url = f"https://www.fincaraiz.com.co{href}" if href and href.startswith("/") else href16 unmodified lineslog_visible += "🔄 Escaneando Metrocuadrado...\n"page.goto(url_mc, wait_until="domcontentloaded", timeout=60000)for _ in range(5):page.mouse.wheel(0, 1000)time.sleep(1.5)30 unmodified linesif not resultados:return f"{log_visible}\n❌ NO SE ENCONTRARON DATOS VÁLIDOS.", None, None, "---"# --- LIMPIEZA Y SELECCIÓN ---df_crudo = pd.DataFrame(resultados)df_limpio = df_crudo.drop_duplicates(subset=['URL'])df_fr = df_limpio[df_limpio['Portal'] == 'Finca Raiz'].head(6)df_mc = df_limpio[df_limpio['Portal'] == 'Metrocuadrado'].head(6)df_final = pd.concat([df_fr, df_mc]).reset_index(drop=True)log_visible += f"\n✨ PROCESADO FINAL: {len(df_final)} inmuebles únicos seleccionados para el reporte."
app.py+9-18