The following example AppleScript code will open a new Safari window to the designated URL, wait for the page to finish loading, then click the Export Data link to download the FanGraphs Leaderboard.csv file.
Note: This was tested on macOS High Sierra, however for macOS Mojave and later there is a note in the waitForPageToFinishLoadingInSafari()
handler to modify its code. Don't forget to do it if applicable.
To use JavaScript with AppleScript and Safari the Allow JavaScript from Apple Events on the Safari > Develop menu, which is hidden by default, must be checked. It can be shown by checking [√] Show Develop menu in menu bar in: Safari > Preferences… > Advanced
set theURL to "https://www.fangraphs.com/leaders.aspx?pos=all&stats=bat&lg=all&qual=50&type=c%2c6%2c11%2c12%2c13%2c21%2c23%2c39%2c35%2c34%2c41%2c42%2c43%2c104%2c107%2c110%2c206%2c209%2c211%2c50%2c61&season=2019&month=0&season1=2019&ind=0&team=0&rost=0&age=0&filter=&players=0"
tell application "Safari" to ?
make new document with properties {URL:theURL}
my waitForPageToFinishLoadingInSafari()
my clickId("LeaderBoard1_cmdCSV")
-- # Handlers:
to clickId(ElementID)
tell application "Safari"
do JavaScript "document.getElementById('" & ElementID & "').click();" in document 1
end tell
end clickId
on waitForPageToFinishLoadingInSafari()
-- # NOTE: For macOS Mojave and later, change 'UI element 1' to 'UI element 2` in the code below.
tell application "System Events"
repeat until (accessibility description of ?
button 1 of UI element 1 of every group of toolbar 1 of window 1 of ?
process "Safari" whose name = "Reload this page") contains "Reload this page"
delay 0.5
end repeat
end tell
end waitForPageToFinishLoadingInSafari
Note: The example AppleScript code is just that and does not contain any error handling as may be appropriate. The onus is upon the user to add any error handling as may be appropriate, needed or wanted. Have a look at the try statement and error statement in the AppleScript Language Guide. See also, Working with Errors. Additionally, the use of the delay command may be necessary between events where appropriate, e.g. delay 0.5
, with the value of the delay set appropriately.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…