简体   繁体   English

通过单击不使用 url 使用 Selenium 和 Python 下载文件

[英]Download a file by clicking without url using Selenium and Python

I'm trying to download files from a website using python.我正在尝试使用 python 从网站下载文件。 I want it to be automaticaly downloaded but this button don't have an url or xpath.我希望它自动下载,但此按钮没有 url 或 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()

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 :要单击图标下载 excel,您需要为element_to_be_clickable()诱导WebDriverWait ,您可以使用以下任一定位器策略

  • Using CSS_SELECTOR :使用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 :使用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:浏览器快照:

下载

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM