单击 "javascript:__doPostBack('LeaderBoard1$cmdCSV','')" 使用 Selenium 下载文件

Use Selenium to download file by clicking "javascript:__doPostBack('LeaderBoard1$cmdCSV','')"

有一堆棒球统计数据的 CSV 文件我想通过自动化下载,可以在以下位置找到:https://www.fangraphs.com/leaders.aspx?pos=all&stats=bat&lg=all&qual=0&type=0&season=2020&month=0&season1=2020&ind=0&team=0&rost=0&age=0&filter=&players=0&startdate=2020-01-01&enddate=2020-12-31。将 table 下载为 CSV 文件的按钮标记为 'Export Data'.

HTML:

<div class="br_dby">
    <span style="float: left">
        <a href="javascript:ShowHide();">Show Filters</a>  
            |  
        <a href="#custom">Custom Reports</a>
    </span>
    <a href="javascript:__doPostBack('LeaderBoard1$cmdCSV','')" id="LeaderBoard1_cmdCSV">Export Data</a>
</div>

如您所知,该按钮不是重定向到下载页面(在这种情况下 requests 可用于下载文件),而是一个过程。

代码:

from selenium import webdriver
from selenium.webdriver.firefox.options import Options
binary = r'C:\Program Files\Mozilla Firefox\firefox.exe'
options = Options()
options.headless = True
options.binary = binary
options.set_preference("browser.download.folderList",2)
options.set_preference("browser.download.manager.showWhenStarting", True)
options.set_preference("browser.download.dir", r"C:\Users\jlpyt\Downloads")
driver = webdriver.Firefox(options=options, executable_path=r"C:\Users\jlpyt\geckodriver-v0.27.0-win32\geckodriver.exe")
driver.get('https://www.fangraphs.com/leaders.aspx?pos=all&stats=bat&lg=all&qual=0&type=0&season=2020&month=0&season1=2020&ind=0&team=0&rost=0&age=0&filter=&players=0&startdate=2020-01-01&enddate=2020-12-31')
elem = driver.find_element_by_id('LeaderBoard1_cmdCSV')
elem.click()

使用此代码,Selenium 可以单击按钮,但不会启动下载。有什么方法可以使用 Selenium 单击按钮并下载文件吗?或者,有什么我没有想到的替代方法吗?

元素为 enabled element, so to click on the element you need to induce for the element_to_be_clickable() and you can use either of the following :

  • 使用ID:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, "LeaderBoard1_cmdCSV"))).click()
    
  • 使用LINK_TEXT:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.LINK_TEXT, "Export Data"))).click()
    
  • 使用CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a#LeaderBoard1_cmdCSV"))).click()
    
  • 使用XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@id='LeaderBoard1_cmdCSV']"))).click()
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
  • 浏览器快照:


参考资料

您可以在以下位置找到一些相关讨论: