[Python] Download button click with Selenium isn’t triggering Excel file download

Discussão em 'Python' iniciado por Stack, Abril 16, 2025.

  1. Stack

    Stack Membro Participativo

    I’m using Selenium (Edge) to automate access to my freight‑forwarder’s web portal. The script successfully:

    Logs in automatically

    Clicks the search button

    Waits for the results table to load

    After that, I need to click the “…” button on a result row to open a context menu, then click Download to grab an Excel file. But the download never starts.

    Perhaps there’s an easier way to trigger the download? Any ideas or pointers on what I’m doing wrong would be greatly appreciated!

    Code:

    from selenium import webdriver
    from selenium.webdriver.edge.service import Service
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    import os
    import time

    # ==============================================
    # Direct credentials (no .env)
    # ==============================================
    username = "xxxxx"
    password = "xxxxxx"

    # Path to msedgedriver (matching installed Edge version)
    driver_path = r'C:\Users\PHacker\AppData\Local\SeleniumBasic\edgedriver.exe'
    service = Service(driver_path)

    # Configure Edge for automatic downloads
    download_dir = r"C:\Users\PHacker\Downloads"
    options = webdriver.EdgeOptions()
    options.add_experimental_option("prefs", {
    "download.default_directory": download_dir,
    "download.prompt_for_download": False,
    "download.directory_upgrade": True,
    "safebrowsing.enabled": True
    })

    driver = webdriver.Edge(service=service, options=options)
    url = "https://lots.logwin-logistics.com/scm/dynamic.xhtml"

    try:
    # 1) Open login page
    driver.get(url)

    # 2) Enter credentials and login
    username_input = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.ID, "loginForm:username"))
    )
    password_input = driver.find_element(By.ID, "loginForm:password")
    stay_signed_in_checkbox = driver.find_element(By.CLASS_NAME, "ui-chkbox-box")
    login_button = driver.find_element(By.XPATH, "//span[text()='Login']")

    username_input.send_keys(username)
    password_input.send_keys(password)
    stay_signed_in_checkbox.click()
    login_button.click()

    WebDriverWait(driver, 10).until(EC.url_changes(url))
    print("Login successful.")

    # 3) Click the search button
    search_button = WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable((By.CLASS_NAME, "la-search"))
    )
    search_button.click()

    # 4) Wait for real rows to appear
    WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.ID, "searchForm:shipmentsTable"))
    )
    for _ in range(10):
    rows = driver.find_elements(
    By.XPATH,
    "//tbody[@id='searchForm:shipmentsTable:tbl_data']/tr[not(contains(@class, 'ui-datatable-empty-message'))]"
    )
    if rows:
    break
    time.sleep(1)
    if not rows:
    raise Exception("No results found to download.")

    # 5) Click the “…” button
    more_btn = WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable((By.CLASS_NAME, "la-ellipsis-v"))
    )
    driver.execute_script("arguments[0].click();", more_btn)

    # 6) Force menu visible
    menu = driver.find_element(By.XPATH, "//*[contains(@id, 'menuEXTENSIONResult_menu')]")
    menu_id = menu.get_attribute("id")
    driver.execute_script(f"document.getElementById('{menu_id}').style.display = 'block';")

    # 7) Click “Download”
    download_option = WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable(
    (By.XPATH, "//span[contains(@class, 'ui-menuitem-text') and normalize-space(text())='Download']")
    )
    )
    driver.execute_script("arguments[0].click();", download_option)

    # 8) Monitor download folder
    timeout = 30
    for _ in range(timeout):
    if any(f.endswith((".csv", ".xlsx", ".xls", ".txt")) for f in os.listdir(download_dir)):
    print("Download detected!")
    break
    time.sleep(1)
    else:
    print("No download detected after 30 seconds.")

    # Keep browser open for inspection
    time.sleep(30)

    except Exception as e:
    print("Error during process:", e)
    finally:
    print("Finished. Browser remains open.")

    # driver.quit() # optionally close browser at end

    -----
    What I’ve tried so far:

    Scrolling into view and clicking via JavaScript

    Forcing the context menu to be visible

    Increasing waits/timeouts


    Questions:

    Is there a simpler way to trigger the download?

    Am I missing a step to ensure the “Download” click actually fires?

    Any tips on debugging PrimeFaces menus with Selenium?

    enter image description here

    Thanks in advance for any help!

    Continue reading...

Compartilhe esta Página