Search code examples
python-3.xweb-scrapingselenium-chromedriver

How to download a file without available link but using selenium on click element


I'm trying to download automatically .zip file from a website using Selenium and Python

This is the code I tried to run :

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains

options = webdriver.ChromeOptions()

prefs = {"download.default_directory" : "C:/Users/toto/Downloads"}

options.add_experimental_option("prefs",prefs)

driver = webdriver.Chrome(options=options)

options = webdriver.ChromeOptions()

url = 'https://open.efsa.europa.eu/study-inventory/EFSA-Q-2022-00556'
driver.get(url)

downloadfiles = driver.find_element(By.XPATH, "//button[contains(text(),'Download all evidences')]")

downloadfiles.click()

driver.implicitly_wait(10)

driver. Quit()

I already tried using CLASS_NAME and XPATH with //span but I did not succeed.


Solution

  • Assuming you have a working Selenium installation:

    [...]
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    [...]
    ## define driver here, then
    wait = WebDriverWait(driver, 5)
    url = 'https://open.efsa.europa.eu/study-inventory/EFSA-Q-2022-00556'
    driver.get(url)
    
    wait.until(EC.element_to_be_clickable((By.XPATH, '//span[text()="Download all evidences"]'))).click()
    try:
        wait.until(EC.element_to_be_clickable((By.XPATH, '//span[text()="I have read and I accept the terms"]'))).click()
    except Exception as e:
        print('no confirmation needed')
    print('done downloading')
    

    Files will be downloaded -- ZIPped.

    You can find Selenium documentation here.