Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -20,7 +20,7 @@ except ImportError:
|
|
| 20 |
subprocess.run(["pip", "install", "fake-useragent"], check=True)
|
| 21 |
from fake_useragent import UserAgent
|
| 22 |
|
| 23 |
-
# --- 1. GENERADOR DE URLS (CORREGIDO
|
| 24 |
def construir_urls_final(zona, ciudad, tipo, hab, ban, park, antiguedad):
|
| 25 |
mapa_ant = {
|
| 26 |
"Menos de 1 año": "de-0-a-1-anos",
|
|
@@ -36,17 +36,16 @@ def construir_urls_final(zona, ciudad, tipo, hab, ban, park, antiguedad):
|
|
| 36 |
z_slug = zona.lower().strip().replace(" ", "-")
|
| 37 |
c_slug = ciudad.lower().strip().replace(" ", "-")
|
| 38 |
|
| 39 |
-
# URL FINCA RAÍZ
|
| 40 |
url_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}"
|
| 41 |
|
| 42 |
-
# URL METROCUADRADO
|
| 43 |
-
url_mc = f"https://www.metrocuadrado.com/{tipo.lower()}-casa-oficina/arriendo/{c_slug}/{int(ban)}-banos-{int(hab)}-habitaciones/?search=form"
|
| 44 |
|
| 45 |
return url_fr, url_mc
|
| 46 |
|
| 47 |
# --- 2. EXTRACTOR DE PRECIO (REGEX) ---
|
| 48 |
def extraer_precio_regex(texto):
|
| 49 |
-
# Detecta $ 1.500.000 o $1500000
|
| 50 |
patron = r'\$\s?(\d{1,3}(?:[.,]\d{3})*)'
|
| 51 |
coincidencias = re.findall(patron, texto)
|
| 52 |
if coincidencias:
|
|
@@ -63,7 +62,6 @@ def motor_tramitia_final(zona, ciudad, area, tipo, hab, ban, park, antiguedad):
|
|
| 63 |
ua = UserAgent()
|
| 64 |
|
| 65 |
with sync_playwright() as p:
|
| 66 |
-
# Lanzamos navegador con perfil de evasión
|
| 67 |
browser = p.chromium.launch(
|
| 68 |
headless=True,
|
| 69 |
args=[
|
|
@@ -71,7 +69,7 @@ def motor_tramitia_final(zona, ciudad, area, tipo, hab, ban, park, antiguedad):
|
|
| 71 |
'--no-sandbox',
|
| 72 |
'--disable-infobars',
|
| 73 |
'--window-position=0,0',
|
| 74 |
-
f'--user-agent={ua.random}'
|
| 75 |
]
|
| 76 |
)
|
| 77 |
context = browser.new_context(viewport={'width': 1366, 'height': 768})
|
|
@@ -82,24 +80,21 @@ def motor_tramitia_final(zona, ciudad, area, tipo, hab, ban, park, antiguedad):
|
|
| 82 |
log_visible += "🔄 Escaneando Finca Raíz...\n"
|
| 83 |
page.goto(url_fr, wait_until="domcontentloaded", timeout=60000)
|
| 84 |
|
| 85 |
-
# Movimiento humano
|
| 86 |
page.mouse.move(random.randint(100, 500), random.randint(100, 500))
|
| 87 |
for _ in range(4):
|
| 88 |
page.mouse.wheel(0, 1000)
|
| 89 |
-
time.sleep(1.5)
|
| 90 |
|
| 91 |
-
# Buscamos enlaces (Links <a>)
|
| 92 |
elementos = page.query_selector_all("a")
|
| 93 |
cont_fr = 0
|
| 94 |
|
| 95 |
-
# Extraemos hasta 15 para tener margen de descarte
|
| 96 |
for el in elementos:
|
| 97 |
if cont_fr >= 15: break
|
| 98 |
txt = el.inner_text()
|
| 99 |
|
| 100 |
if "$" in txt:
|
| 101 |
precio = extraer_precio_regex(txt)
|
| 102 |
-
if precio > 600000:
|
| 103 |
href = el.get_attribute("href")
|
| 104 |
full_url = f"https://www.fincaraiz.com.co{href}" if href and href.startswith("/") else href
|
| 105 |
|
|
@@ -122,7 +117,7 @@ def motor_tramitia_final(zona, ciudad, area, tipo, hab, ban, park, antiguedad):
|
|
| 122 |
log_visible += "🔄 Escaneando Metrocuadrado...\n"
|
| 123 |
page.goto(url_mc, wait_until="domcontentloaded", timeout=60000)
|
| 124 |
|
| 125 |
-
for _ in range(5):
|
| 126 |
page.mouse.wheel(0, 1000)
|
| 127 |
time.sleep(1.5)
|
| 128 |
|
|
@@ -159,17 +154,13 @@ def motor_tramitia_final(zona, ciudad, area, tipo, hab, ban, park, antiguedad):
|
|
| 159 |
if not resultados:
|
| 160 |
return f"{log_visible}\n❌ NO SE ENCONTRARON DATOS VÁLIDOS.", None, None, "---"
|
| 161 |
|
| 162 |
-
# --- LIMPIEZA Y SELECCIÓN
|
| 163 |
df_crudo = pd.DataFrame(resultados)
|
| 164 |
-
|
| 165 |
-
# 1. Eliminar duplicados exactos de URL
|
| 166 |
df_limpio = df_crudo.drop_duplicates(subset=['URL'])
|
| 167 |
|
| 168 |
-
# 2. Seleccionar top 6 por portal
|
| 169 |
df_fr = df_limpio[df_limpio['Portal'] == 'Finca Raiz'].head(6)
|
| 170 |
df_mc = df_limpio[df_limpio['Portal'] == 'Metrocuadrado'].head(6)
|
| 171 |
|
| 172 |
-
# 3. Combinar
|
| 173 |
df_final = pd.concat([df_fr, df_mc]).reset_index(drop=True)
|
| 174 |
|
| 175 |
log_visible += f"\n✨ PROCESADO FINAL: {len(df_final)} inmuebles únicos seleccionados para el reporte."
|
|
|
|
| 20 |
subprocess.run(["pip", "install", "fake-useragent"], check=True)
|
| 21 |
from fake_useragent import UserAgent
|
| 22 |
|
| 23 |
+
# --- 1. GENERADOR DE URLS (CORREGIDO MC Y FR) ---
|
| 24 |
def construir_urls_final(zona, ciudad, tipo, hab, ban, park, antiguedad):
|
| 25 |
mapa_ant = {
|
| 26 |
"Menos de 1 año": "de-0-a-1-anos",
|
|
|
|
| 36 |
z_slug = zona.lower().strip().replace(" ", "-")
|
| 37 |
c_slug = ciudad.lower().strip().replace(" ", "-")
|
| 38 |
|
| 39 |
+
# URL FINCA RAÍZ
|
| 40 |
url_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}"
|
| 41 |
|
| 42 |
+
# URL METROCUADRADO CORREGIDA (Se añade {z_slug})
|
| 43 |
+
url_mc = f"https://www.metrocuadrado.com/{tipo.lower()}-casa-oficina/arriendo/{c_slug}/{z_slug}/{int(ban)}-banos-{int(hab)}-habitaciones/?search=form"
|
| 44 |
|
| 45 |
return url_fr, url_mc
|
| 46 |
|
| 47 |
# --- 2. EXTRACTOR DE PRECIO (REGEX) ---
|
| 48 |
def extraer_precio_regex(texto):
|
|
|
|
| 49 |
patron = r'\$\s?(\d{1,3}(?:[.,]\d{3})*)'
|
| 50 |
coincidencias = re.findall(patron, texto)
|
| 51 |
if coincidencias:
|
|
|
|
| 62 |
ua = UserAgent()
|
| 63 |
|
| 64 |
with sync_playwright() as p:
|
|
|
|
| 65 |
browser = p.chromium.launch(
|
| 66 |
headless=True,
|
| 67 |
args=[
|
|
|
|
| 69 |
'--no-sandbox',
|
| 70 |
'--disable-infobars',
|
| 71 |
'--window-position=0,0',
|
| 72 |
+
f'--user-agent={ua.random}'
|
| 73 |
]
|
| 74 |
)
|
| 75 |
context = browser.new_context(viewport={'width': 1366, 'height': 768})
|
|
|
|
| 80 |
log_visible += "🔄 Escaneando Finca Raíz...\n"
|
| 81 |
page.goto(url_fr, wait_until="domcontentloaded", timeout=60000)
|
| 82 |
|
|
|
|
| 83 |
page.mouse.move(random.randint(100, 500), random.randint(100, 500))
|
| 84 |
for _ in range(4):
|
| 85 |
page.mouse.wheel(0, 1000)
|
| 86 |
+
time.sleep(1.5)
|
| 87 |
|
|
|
|
| 88 |
elementos = page.query_selector_all("a")
|
| 89 |
cont_fr = 0
|
| 90 |
|
|
|
|
| 91 |
for el in elementos:
|
| 92 |
if cont_fr >= 15: break
|
| 93 |
txt = el.inner_text()
|
| 94 |
|
| 95 |
if "$" in txt:
|
| 96 |
precio = extraer_precio_regex(txt)
|
| 97 |
+
if precio > 600000:
|
| 98 |
href = el.get_attribute("href")
|
| 99 |
full_url = f"https://www.fincaraiz.com.co{href}" if href and href.startswith("/") else href
|
| 100 |
|
|
|
|
| 117 |
log_visible += "🔄 Escaneando Metrocuadrado...\n"
|
| 118 |
page.goto(url_mc, wait_until="domcontentloaded", timeout=60000)
|
| 119 |
|
| 120 |
+
for _ in range(5):
|
| 121 |
page.mouse.wheel(0, 1000)
|
| 122 |
time.sleep(1.5)
|
| 123 |
|
|
|
|
| 154 |
if not resultados:
|
| 155 |
return f"{log_visible}\n❌ NO SE ENCONTRARON DATOS VÁLIDOS.", None, None, "---"
|
| 156 |
|
| 157 |
+
# --- LIMPIEZA Y SELECCIÓN ---
|
| 158 |
df_crudo = pd.DataFrame(resultados)
|
|
|
|
|
|
|
| 159 |
df_limpio = df_crudo.drop_duplicates(subset=['URL'])
|
| 160 |
|
|
|
|
| 161 |
df_fr = df_limpio[df_limpio['Portal'] == 'Finca Raiz'].head(6)
|
| 162 |
df_mc = df_limpio[df_limpio['Portal'] == 'Metrocuadrado'].head(6)
|
| 163 |
|
|
|
|
| 164 |
df_final = pd.concat([df_fr, df_mc]).reset_index(drop=True)
|
| 165 |
|
| 166 |
log_visible += f"\n✨ PROCESADO FINAL: {len(df_final)} inmuebles únicos seleccionados para el reporte."
|