pythonseleniumselenium-webdriverwebdriverwaitdopostback

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


There are a bunch of CSV files of baseball stats that I want to download via automation, which can be found at: 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. The button to download the table as a CSV is labeled '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>

As you can tell, the button is not a redirect to a download page (in which case requests could be used to download the file), but is a process.

Code:

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()

Using this code, Selenium is able to click the button, but no download is initiated. Is there some way that I can use Selenium to click the button and download the file? Or, is there some alternative method that I have not thought of?


Solution

  • The element is __doPostBack enabled element, so to click on the element you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

    fangraphs


    References

    You can find a couple of relevant discussions in: