import time
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.common.exceptions import TimeoutException, WebDriverException
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
def scrape_restaurantes_info(url):
if not url:
print("Error: URL vacía.")
return None
driver = None
try:
service = Service(ChromeDriverManager().install())
options = webdriver.ChromeOptions()
# CAMBIO CLAVE: Comentamos el modo Headless para que la ventana se abra.
# Esto permite que Cloudflare valide tu entorno como un "Humano Real" con monitor.
# options.add_argument("--headless")
options.add_argument("--no-sandbox")
options.add_argument("--disable-dev-shm-usage")
# Cambiamos a un User Agent común y corriente de una máquina Windows estándar
options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
# Parámetros para mitigar la bandera de automatización
options.add_argument("--disable-blink-features=AutomationControlled")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option("useAutomationExtension", False)
# Evita conflictos de puertos locales de depuración
options.add_argument("--remote-debugging-port=9222")
driver = webdriver.Chrome(service=service, options=options)
# Borramos el rastro del objeto webdriver en el navegador
driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
"source": "Object.defineProperty(navigator, 'webdriver', {get: () => undefined})"
})
# Maximizamos la ventana para simular un comportamiento de navegación típico
driver.maximize_window()
driver.set_page_load_timeout(45)
except Exception as e:
print(f"Error al inicializar el driver: {e}")
if driver: driver.quit()
return None
try:
print(f"Tratando de cargar la página con Selenium (Modo Visible): {url}")
driver.get(url)
# Esperamos 8 segundos completos en pantalla para que la página renderice todo
print("Esperando la carga de componentes asincrónicos...")
time.sleep(8)
response_text = driver.page_source
soup = BeautifulSoup(response_text, "html.parser")
return soup
except Exception as e:
print(f"Error durante el raspado: {e}")
return None
finally:
if driver:
print("Cerrando el navegador de forma segura...")
driver.quit()
# --- EJECUCIÓN CON LA URL DE LISTADO GENERAL ---
tripadvisor_url_listado = "https://www.tripadvisor.com/Restaurants-g150813-zfp10955-Tulum_Yucatan_Peninsula.html"
soup_tripadvisor = scrape_restaurantes_info(tripadvisor_url_listado)
if soup_tripadvisor:
print("\n ¡HTML obtenido con éxito!")
page_title_tag = soup_tripadvisor.find("title")
if page_title_tag:
print(f" Título Real Obtenido: {page_title_tag.get_text(strip=True)}")
else:
print("No se encontró la etiqueta <title>.")
else:
print("Falla al raspar la página.")
print("-" * 50)