Go to website, download pdfs and move them to correct folder

Hi everyone! I recently finished a code that:

  1. Goes to website (Safari, but Chrome possible)
  2. Presses a button in the website to download pdf
  3. Moves pdf to correct folder
  4. repeats

It’s useful for anyone trying to automatize downloading pdfs from a website (I’m currently using it for that).

Hope it’ll help anyone!!



set info1 to {LIST} 
set info2 to {LIST}

to goToWebPage(theWebPage)
	tell application "Safari"
		activate
		open location theWebPage
	end tell
end goToWebPage

to clickClassName(theClassName, elementnum)
	tell application "Safari"
		do JavaScript "document.getElementsByClassName('" & theClassName & "')[" & elementnum & "].click();" in document 1
	end tell
end clickClassName

info1 as Unicode text
info2 as Unicode text

with timeout of 30000000 seconds
	
	repeat with theItem in info1
		set iteminfo1 to theItem
		
		repeat with theItem in info2
			set iteminfo2 to theItem
				
				goToWebPage("WEBSITE.com/" & iteminfo1 & "/" & iteminfo2)
				
				tell application "Safari"
					repeat while document 1's source = ""
						delay 0.5
					end repeat
				end tell
								
				clickClassName("BUTTON", 0)
					
				delay (10)
					
				set thisFile to "/Users/macbookpro/Downloads/" & iteminfo1 & "-" & iteminfo2 & ".pdf" as string
				set thatPath to "/Users/macbookpro/Documentos/" & (iteminfo1) & "/" (iteminfo2) & "/" as string
					
				try
					if exists POSIX file thisFile as string then
					tell application "Finder" to set the clipboard to POSIX file thisFile as string
					end if
						
					if exists POSIX file thatPath as string then
					tell application "Finder" to move file (the clipboard) to POSIX file thatPath with replacing
					end if
				end try	
			
				try
					tell application "Safari"
						delete tab 1 of window 1
					end tell
				end try
										
		end repeat
		
	end repeat
	
end timeout

I also tried to add some error management aspects, but failed hehe.

I’ll probably translate it to python as I need to create a windows compatible version, but in the meantime feel free to use this code.

See ya!