from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup
import time

def main():
    # Configura Chrome en modo headless y con ajustes para entornos Linux/servidores
    chrome_options = Options()
    chrome_options.add_argument("--headless")
    chrome_options.add_argument("--no-sandbox")
    chrome_options.add_argument("--disable-dev-shm-usage")

    # Ajusta la ruta a tu chromedriver si es necesario
    service = Service('/usr/local/bin/chromedriver')
    driver = webdriver.Chrome(service=service, options=chrome_options)

    # URL de la página que deseas scrapear
    url = "https://optioncharts.io/trending/high-iv-rank-stocks"
    driver.get(url)

    try:
        # Espera hasta que aparezca la tabla (hasta 20s)
        WebDriverWait(driver, 20).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, "table.table.table-sm.table-hover"))
        )
        # Pausa adicional para asegurar que el contenido dinámico se cargue
        time.sleep(2)
    except Exception as e:
        print("No se pudo cargar la tabla:", e)
        driver.quit()
        return

    # Obtén el HTML renderizado
    html = driver.page_source
    driver.quit()

    # Parseamos el HTML con BeautifulSoup
    soup = BeautifulSoup(html, 'html.parser')

    # Busca la tabla por sus clases
    table = soup.find("table", class_="table table-sm table-hover")
    if not table:
        print("No se encontró la tabla con la clase 'table table-sm table-hover'.")
        return

    # Localiza el cuerpo de la tabla (tbody)
    tbody = table.find("tbody")
    if not tbody:
        print("No se encontró el <tbody> en la tabla.")
        return

    # Recorre cada fila del <tbody> y extrae la primera columna (símbolo)
    rows = tbody.find_all("tr")
    if not rows:
        print("No se encontraron filas en el <tbody>.")
        return

    for row in rows:
        cols = row.find_all("td")
        if len(cols) > 0:
            # Asumiendo que la primera columna es el símbolo
            symbol = cols[0].get_text(strip=True)
            print("Symbol:", symbol)

if __name__ == "__main__":
    main()
