Download a file by clicking without url using Selenium and Python

Question:

I’m trying to download files from a website using python. I want it to be automaticaly downloaded but this button don’t have an url or xpath. I tried this code but I didn’t found a good result :

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
download_dir = 'C:/Users/ASUS/Documents/data'

driver = webdriver.Chrome("C:/chrome/chromedriver.exe")
driver.get("http://www.ins.tn/statistiques/90#")
button = driver.find_element_by_class_name('btnexport')
button.click()
Asked By: Monica

||

Answers:

To click on the icon to download the excel you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following locator strategies:

  • Using CSS_SELECTOR:

    driver.execute("get", {'url': 'http://www.ins.tn/statistiques/90#'})
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.export a.btnexport[id^='btnExporttoExcel']"))).click()
    
  • Using XPATH:

    driver.execute("get", {'url': 'http://www.ins.tn/statistiques/90#'})
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='export']//a[@class='btnexport  ' and starts-with(@id, 'btnExporttoExcel')]"))).click()
    
  • Note: You have to add the following imports :

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
  • Browser Snapshot:

download

Answered By: undetected Selenium