Get data from webpage via Apple script - applescript

I'm trying to get the data of Crypto name, Price, and % from the webpage https://www.worldcoinindex.com/
How can i get the % column value via the following scripts?
set theHtml to do shell script "curl -s " & quoted form of "https://www.worldcoinindex.com"
set text item delimiters to {"<tbody>", "</tbody>"}
set tableContents to theHtml's text item 2 # item 2 is the body of the price table
set text item delimiters to {"<h2>"} # site uses new h2 for each currency
set tableChunks to tableContents's text items 2 thru -1
set pasteStr to ""
repeat with aChunk in tableChunks
set text item delimiters to "><span>$ </span><span class=\"span\">"
tell aChunk's text item 1 to set {theSymbol, thePrice} to {first word, last word}
set pasteStr to pasteStr & theSymbol & tab & thePrice & return
end repeat
set the clipboard to pasteStr

Here is an alternate way for your consideration:
Note that this requires Allow JavaScript from Apple Events to be checked on the hidden Develop menu in Safari.
To unhide the hidden Develop menu:
Safari > Preferences… > Advanced > [√] Show Develop menu in menu bar
Example AppleScript code:
tell application "Safari"
make new document ¬
with properties {URL:"https://www.worldcoinindex.com"}
my waitForSafariPageToFinishLoading()
tell front document
set tickerList to {}
set lastPriceList to {}
set percentageList to {}
repeat with i from 0 to 99
set ticker to ¬
do JavaScript ¬
"document.getElementsByClassName('ticker')[" & i & "].innerText;"
copy words of ticker as text to end of tickerList
set lastPrice to ¬
do JavaScript ¬
"document.getElementsByClassName('number pricekoers lastprice')[" & i & "].innerText;"
copy lastPrice to end of lastPriceList
set percentage to ¬
do JavaScript ¬
"document.getElementsByClassName('percentage')[" & i & "].innerText;"
copy percentage to end of percentageList
end repeat
end tell
end tell
set tempListItem to {}
set groupedItemsList to {}
repeat with i from 1 to 100
copy item i of tickerList to end of tempListItem
copy item i of lastPriceList to end of tempListItem
copy item i of percentageList to end of tempListItem
copy tempListItem to end of groupedItemsList
set tempListItem to {}
end repeat
set tabDelimitatedListAsText to ""
repeat with anItem in groupedItemsList
set {TID, AppleScript's text item delimiters} to ¬
{AppleScript's text item delimiters, tab}
set thisItem to text of anItem as text
set AppleScript's text item delimiters to TID
set tabDelimitatedListAsText to ¬
tabDelimitatedListAsText & thisItem & linefeed
end repeat
set the clipboard to tabDelimitatedListAsText
on waitForSafariPageToFinishLoading()
-- # Wait for page to finish loading in Safari.
-- # This works in macOS Catalina and
-- # macOS Big Sur and may need adjusting
-- # for other versions of macOS.
tell application "System Events" to repeat until ¬
exists (buttons of groups of toolbar 1 of window 1 of ¬
process "Safari" whose name = "Reload this page")
delay 0.5
end repeat
end waitForSafariPageToFinishLoading
Note: The example AppleScript code is just that and sans any included error handling does not contain any additional 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.

Related

Applescript - Check if Page Content of URLs List contain THIS_TEXT | Output all these URLs

Trying the following:
My script returns approx. 20 URLs as variable Single_URLs
Check if these URLs contain THIS_TEXT
Keep URL's containing THIS_TEXT
Delete the other URLs from the result
Pure Applescript or Shell.
My example script just checks IF the provided URL contains THIS_TEXT as i could not get any further by now.
--Open Pages
set site_url to "https://teespring.com/shop/CLASSIC-DODGE-CHARGER-MOP?aid=marketplace&tsmac=marketplace&tsmic=search#pid=212&cid=5819&sid=front"
tell application "Safari"
activate
open location site_url
end tell
-- wait until page loaded
property testingString : "CLASSIC DODGE CHARGER" --Text on website to look for
set pageLoaded to false
tell application "Safari"
repeat while pageLoaded is false
set readyState to (do JavaScript "document.readyState" in document 1)
set pageText to text of document 1
if (readyState is "complete") and (pageText contains testingString) then set pageLoaded to true
delay 0.2
end repeat
end tell
-- get number of links
set theLinks to {}
tell application "Safari" to set num_links to (do JavaScript "document.links.length" in document 1)
set linkCounter to num_links - 1
-- retrieve the links
repeat with i from 0 to linkCounter
tell application "Safari" to set end of theLinks to do JavaScript "document.links[" & i & "].href" in document 1
end repeat
theLinks
set nonExcludedURLs to {}
pageLoaded
This is a a charitable project to help Artists not being cheated. Every help is very welcome, Thanks.
Here's a script that would do that with AppleScript:
use AppleScript version "2.4" -- Yosemite (10.10) or later
use scripting additions
on run
set URLFoundItems to {}
set SearchItemsList to {"CLASSIC DODGE CHARGER"}
set URLList to {"https://teespring.com/shop/CLASSIC-DODGE-CHARGER-MOP?aid=marketplace&tsmac=marketplace&tsmic=search#pid=212&cid=5819&sid=front"}
repeat with i from 1 to count of URLList
set URLv to item i of URLList
tell application "Safari"
try
tell window 1
set current tab to (make new tab with properties {URL:URLv})
end tell
on error
make new document with properties {URL:URLv}
end try
set readyState to (do JavaScript "document.readyState" in document 1)
set pageLoaded to false
repeat while pageLoaded is false
set readyState to (do JavaScript "document.readyState" in document 1)
set SearchIn to source of document 1
if (readyState is "complete") and SearchIn ≠ "" then
set pageLoaded to true
else
delay 0.2
end if
end repeat
repeat with z from 1 to count of SearchItemsList
set SearchString to item z of SearchItemsList
set x to offset of SearchString in SearchIn
if x > 0 then
set URLFoundItems to URLFoundItems & URLv & " (" & SearchString & ")" as string
end if
end repeat
tell window 1
close current tab
end tell
end tell
end repeat
return URLFoundItems
end run
I hope this helps.

How to open a text file and rename it with the text from the file?

I am trying to rename some text files with applescript using a string that is in the text of the file. The files are old usenet messages that ended up with severely messed up names like REARIY-1. I have figured out how to read the file and find the text string I want (it is proceeded by SUBJECT:) I have also figured out how to rename a file if I have the user type in the text, but I have had trouble opening the file to read it and also getting the path to allow me to rename it.
The best I have done so far is the following (which required the user to be careful to select the same file twice):
set foo to choose file with multiple selections allowed
set fileAlias to foo as alias
set footext to read file ((choose file with prompt "phhhht") as string)
set targetText to "Subject:"
set extractedProperty to ""
set foundIt to "Target text not found."
set oldDelims to AppleScript's text item delimiters
try
set AppleScript's text item delimiters to {ASCII character 13}
set bar to text items of footext
repeat with thisItem in bar
if thisItem contains targetText then
set foundIt to thisItem
exit repeat
end if
end repeat
set AppleScript's text item delimiters to oldDelims
on error
set AppleScript's text item delimiters to oldDelims
end try
try
if thisItem contains "not found" then
display dialog "text not found, filename not changed"
tell me to quit
end if
end try
repeat with thisWord in words of foundIt
if contents of thisWord is not targetText then
set extractedProperty to extractedProperty & thisWord & " "
end if
end repeat
set extractedProperty to characters 9 thru -2 of extractedProperty as text
display dialog extractedProperty -- for check only
tell application "Finder"
set name of fileAlias to (extractedProperty & ".txt")
end tell
You just need to change your third line from:
set foo to choose file with multiple selections allowed
set fileAlias to foo as alias
set footext to read file ((choose file with prompt "phhhht") as string)
to
set footext to read file (foo as string)
You could try something like this.
set fileList to choose file with multiple selections allowed
set targetText to "Subject:"
set targetTextCount to count of characters in targetText
set extractedProperty to ""
repeat with thisItem in fileList
set footext to paragraphs of (read file (thisItem as string))
repeat with this_item in footext
if this_item contains targetText then
set extractedProperty to characters from ((offset of targetText in this_item) + targetTextCount) to -1 of this_item as string
--log extractedProperty
tell application "Finder"
set name of (thisItem as alias) to (extractedProperty & ".txt")
end tell
exit repeat
end if
end repeat
end repeat

Cannot pass handler parameter to code. Newbie

Background: I am trying to pass caller information from a telephony application (Phone Amego) to my Samsung tv using its AllShare feature. In order to do so I have to send a soap message with the caller information. Phone Amego provides an easy way to assign an applescript to call events. But, I have no programming experience whatsoever!
Sofar I have succeeded in making a script which reads a soap message, updates the required fields and sends it to my tv. Perfect, at least the result, the code may not be perfect but it works. Here is the code.
set callerID_string to "John Doe : 1-917-123-4567"
set AppleScript's text item delimiters to {":"}
set pieces to text items of callerID_string
set callerID_name to item 1 of pieces
set callerID_number to item 2 of pieces
set AppleScript's text item delimiters to {""}
set myDate to do shell script "date '+%d.%m.%Y'"
set myTime to do shell script "date '+%T'"
set total_Length to (length of callerID_name) + (length of callerID_number) + 780
set search_strings to {"Content-Length: 796", "2013-01-01", "00:00:00", "Mike", "777-777-7777"}
set replace_strings to {"Content-Length:" & total_Length, myDate, myTime, callerID_name, callerID_number}
tell application "Finder"
set theFile to alias "Macintosh HD:Users:Marc:Desktop:IncCallMBsTemplate.txt"
open for access theFile
set fileRef to open for access (theFile as alias)
set fileContents to (read fileRef)
close access theFile
end tell
set the clipboard to fileContents
repeat with i from 1 to (count search_strings)
set the_string to the clipboard
set the_string to my snr(the_string, item i of search_strings, item i of replace_strings)
end repeat
on snr(the_string, search_string, replace_string)
tell (a reference to my text item delimiters)
set {old_atid, contents} to {contents, search_string}
set {the_string, contents} to {the_string's text items, replace_string}
set {the_string, contents} to {"" & the_string, old_atid}
end tell
set the clipboard to the_string
-- Create a file handler for the file to write to.
set myFile to (open for access alias "Macintosh HD:Users:Marc:Desktop:Test.txt" with write permission)
try
-- Delete current contents of the file
set eof myFile to 0
-- Write to file
write the_string to myFile as «class utf8»
end try
-- Close the file
close access myFile
end snr
set cmd to "/Usr/bin/nc 10.0.1.7 52235 < /Users/Marc/Desktop/Test.txt"
do shell script cmd
Problem: In the script above I have set a value to the variable callerID_string, but I should obtain it from Phone Amego through the handler call_from(callerID_string). But whatever I try, I cannot pass that callerID_string to my code. It consists of 2 parts namely the caller's name and number. The code should start like:
on call_from(callerID_string)
Any help would be highly appreciated.
I assume your script is running with the other app at the same time and it needs that handler and therefore a little re-designing so we can call the (former main) code as a subroutine.
I'm not sure if I understood the situation correctly but here it is anyway:
I added the on call_from... handler which calls the rest of the code as subroutine (myAction).
First commented line in code can be uncommented and used to test-run it with AppleScript Editor. Remove the line when not needed anymore.
testFilePath is a property and globally visible. Also, I changed the hardcoded file-path-stuff so it finds the path to the desktop.
property testFilePath : ""
-- my myAction("John Doe : 1-917-123-4567")
on call_from(callerID_string)
my myAction(callerID_string)
end call_from
on myAction(CIS)
if CIS is "" then
tell me to activate
display dialog "Caller ID is empty." buttons {"Quit"} default button 1 with icon 0
return
end if
set pathToDesktop to (path to desktop) as text
set testFilePath to pathToDesktop & "Test.txt"
set callerID_string to CIS -- "John Doe : 1-917-123-4567"
set lastTextItemDelimeter to AppleScript's text item delimiters
set AppleScript's text item delimiters to {" : "}
set pieces to text items of callerID_string
set callerID_name to item 1 of pieces
set callerID_number to item 2 of pieces
set AppleScript's text item delimiters to {""} -- or lastTextItemDelimeter if you want to change it back to last
set myDate to do shell script "date '+%d.%m.%Y'"
set myTime to do shell script "date '+%T'"
set total_Length to (length of callerID_name) + (length of callerID_number) + 780
set search_strings to {"Content-Length: 796", "2013-01-01", "00:00:00", "Mike", "777-777-7777"}
set replace_strings to {"Content-Length:" & total_Length, myDate, myTime, callerID_name, callerID_number}
set templateFile to pathToDesktop & "IncCallMBsTemplate.txt"
tell application "Finder"
set theFile to templateFile as alias -- Macintosh HD:Users:Marc:Desktop:IncCallMBsTemplate.txt"
open for access theFile
set fileRef to open for access (theFile as alias)
set fileContents to (read fileRef)
close access theFile
end tell
set the clipboard to fileContents
repeat with i from 1 to (count search_strings)
set the_string to the clipboard
set the_string to my snr(the_string, item i of search_strings, item i of replace_strings)
end repeat
set cmd to "/usr/bin/nc 10.0.1.7 52235 < " & quoted form of (POSIX path of testFilePath)
do shell script cmd
end myAction
on snr(the_string, search_string, replace_string)
tell (a reference to my text item delimiters)
set {old_atid, contents} to {contents, search_string}
set {the_string, contents} to {the_string's text items, replace_string}
set {the_string, contents} to {"" & the_string, old_atid}
end tell
set the clipboard to the_string
-- Create a file handler for the file to write to.
set myFile to (open for access (testFilePath as alias) with write permission)
try
-- Delete current contents of the file
set eof myFile to 0
-- Write to file
write the_string to myFile as «class utf8»
on error the error_message number the error_number
-- display dialog "Error: " & the error_number & ". " & the error_message buttons {"Cancel"} default button 1
log "Error: " & the error_number & ". " & the error_message
end try
-- Close the file
close access myFile
end snr

Using Applescript to export list of URLs based on tags?

I am new to Applescript, so I found an awesome script online that will list all Evernote snaps that have an associated URL . For listing all snaps with URLs, this solution is great. How could I modify this script to filter the listed URLs based on specific tags?
Script I am currently using: http://veritrope.com/code/save-a-list-of-urls-from-your-evernote-items-as-a-file/
tell application "Evernote"
activate
set listOfNotebooks to {}
set EVNotebooks to every notebook
repeat with currentNotebook in EVNotebooks
set currentNotebookName to (the name of currentNotebook)
copy currentNotebookName to the end of listOfNotebooks
end repeat
set Folders_sorted to my simple_sort(listOfNotebooks)
set SelNotebook to choose from list of Folders_sorted with title "Select Evernote Notebook" with prompt ¬
"Current Evernote Notebooks" OK button name "OK"
set EVnotebook to item 1 of SelNotebook
set listofNotes to {}
set note_Records to {}
set allNotes to every note in notebook EVnotebook
repeat with currentNote in allNotes
try
set currentNoteURL to (the source URL of currentNote)
set currentNoteTitle to title of currentNote
if currentNoteURL is not missing value then
copy currentNoteURL to the end of listofNotes
copy {name:currentNoteTitle, URL:currentNoteURL} to the end of note_Records
end if
end try
end repeat
set Notes_sorted to my simple_sort(listofNotes)
set SelNote to ¬
choose from list of Notes_sorted with title ¬
"List Of URLs In Notes" OK button name "Export List" cancel button name "Close Window" with empty selection allowed
set record_Text to {}
repeat with note_Record in note_Records
set theCurrentRecord to ("Title: " & name of note_Record & return & "URL: " & URL of note_Record & return & return) as text
copy theCurrentRecord to the end of record_Text
end repeat
if (SelNote is not false) then
tell application "System Events"
-- convert list to text FILE
set ExportList to "Current List of URLs in Notes for " & EVnotebook & "-- " & (current date) & return & return & record_Text as Unicode text
set fn to choose file name with prompt "Name this file" default name "URL List for Notebook Named " & EVnotebook & ¬
".txt" default location (path to desktop folder)
set fid to open for access fn with write permission
write ExportList to fid
close access fid
end tell
else
set EVnotebook to item 1 of SelNotebook
end if
end tell
on simple_sort(my_list)
set the index_list to {}
set the sorted_list to {}
repeat (the number of items in my_list) times
set the low_item to ""
repeat with i from 1 to (number of items in my_list)
if i is not in the index_list then
set this_item to item i of my_list as text
if the low_item is "" then
set the low_item to this_item
set the low_item_index to i
else if this_item comes before the low_item then
set the low_item to this_item
set the low_item_index to i
end if
end if
end repeat
set the end of sorted_list to the low_item
set the end of the index_list to the low_item_index
end repeat
return the sorted_list
end simple_sort
Apologies for my code block being funky. If any mods can fix it I'd appreciate the help.
In your repeat with currentNote in allNotes loop you could add something like this:
set allTags to tags of currentNote
repeat with currentTag in allTags
if name of currentTag is "your_specific_tag" then
do what you want
...........
end if
end repeat

Applescript to repeat complete script for files in a folder

I have managed to get all this code together now and just need the last step to work. Any help would be greatly appreciated.
I have setup this script to open an .xlsx file in a folder, change the date, save it then PDF to another folder. It then creates a mail by looking up the client code (found in the excel file) to subsequently look for this code in a Database.xlsx file and return the e-mail address of the client and add it to the "To" field in mail. It then attaches the newly created PDF to this mail and I can just click and send.
The script stops after the first .xlsx file has been opened, just so I can check the details is correct before it PDF's and creates the mail.
My question is: How do I get this process to repeat for each file in the initial folder? I have tried the repeat function, but to no avail.
Any help would be greatly appreciated.
Thank you.
--Complete script for updating invoice, saving (as PDF too in seperate folder) and e-mailing invoices
--Select the first file in a folder and then repeat for the next
set theFolder to POSIX path of (choose folder with prompt "Choose Folder containing .xlsx invoices")
set theFolderList to list folder theFolder without invisibles
repeat with x from 1 to count of theFolderList
set theFile to theFolder & item x of theFolderList
set theNewFile to theFolder & theFile
tell application "Microsoft Excel"
activate
open theFile
set ActiveClientCode to value of range ("B1")
end tell
--Change date of one cell to date of next month
tell application "Microsoft Excel"
activate
open "/Users/pienaar0/Documents/AdminAssist/" & ActiveClientCode & ".xlsx"
set d to value of cell ("A1")
set d to my MonthAdd(d)
set value of cell ("A1") to d
end tell
on MonthAdd(d)
set m to ((month of d as integer) + 1)
set ddd to day of d
if m > 12 then
set m to m - 12
set year of d to (year of d) + 1
end if
if {m} is in {4, 6, 9, 11} and ddd = 31 then --AppleScript treats "Apr 31" as May 1,
set day of d to 30
end if
set month of d to m
if m = 2 and month of d as integer = 3 then --AppleScript treats "Feb 31" as Mar 3,
set day of d to 1 -- Mar 1
set d to d - (1 * days) -- last day of Feb
end if
return d
end MonthAdd
property dialog_timeout : 36000
display dialog "Make sure the invoice is correct before clicking OK" buttons {"OK"} giving up after dialog_timeout
set the user_choice to the button returned of the result
--Save document and PDF
tell application "Microsoft Excel"
save active workbook
save active workbook in "Macintosh HD:Users:pienaar0:Documents:AdminAssistPDF:" & ActiveClientCode & ".pdf" as PDF file format
end tell
--Find e-mail address, and Name in Database (Check filepath and ranges)
tell application "Microsoft Excel"
open "Users/pienaar0/Documents/Database.xlsx"
set searchRange to range ("D2:D5")
set foundRange to find searchRange what ActiveClientCode with match case
set fRow to first row index of foundRange
set ClientEmail to value of range ("C" & fRow as text)
set ClientFirstname to value of range ("A" & fRow as text)
(* do something with the foundRange *)
end tell
--Create e-mail
tell application "Mail"
set theMessage to make new outgoing message with properties {visible:true, subject:"Your monthly invoice", content:"Dear " & ClientFirstname & ",
I trust this mail finds you well?
Please find attached your monthly invoice for your immediate consideration.
Regards,
AdminAssist
"}
set message signature of theMessage to signature "Replies & Forwards"
delay 1
tell content of theMessage
make new attachment with properties {file name:"/Users/pienaar0/Documents/AdminAssist/PDF/" & ActiveClientCode & " Sheet1.pdf"}
tell theMessage
make new to recipient at end of to recipients with properties {address:ClientEmail}
end tell
end tell
end tell
end repeat
You need to move your handler outside of the repeat block:
property dialog_timeout : 36000
--Complete script for updating invoice, saving (as PDF too in seperate folder) and e-mailing invoices
--Select the first file in a folder and then repeat for the next
set theFolder to POSIX path of (choose folder with prompt "Choose Folder containing .xlsx invoices")
tell application "System Events" to set theFolderList to name of every file of folder theFolder whose visible is true
repeat with x from 1 to count of theFolderList
set theFile to theFolder & item x of theFolderList
set theNewFile to theFolder & theFile
tell application "Microsoft Excel"
activate
open theFile
set ActiveClientCode to value of range ("B1")
end tell
--Change date of one cell to date of next month
tell application "Microsoft Excel"
activate
open "/Users/pienaar0/Documents/AdminAssist/" & ActiveClientCode & ".xlsx"
set d to value of cell ("A1")
set d to my MonthAdd(d)
set value of cell ("A1") to d
end tell
display dialog "Make sure the invoice is correct before clicking OK" buttons {"OK"} giving up after dialog_timeout
set the user_choice to the button returned of the result
--Save document and PDF
tell application "Microsoft Excel"
save active workbook
save active workbook in "Macintosh HD:Users:pienaar0:Documents:AdminAssistPDF:" & ActiveClientCode & ".pdf" as PDF file format
end tell
--Find e-mail address, and Name in Database (Check filepath and ranges)
tell application "Microsoft Excel"
open "Users/pienaar0/Documents/Database.xlsx"
set searchRange to range ("D2:D5")
set foundRange to find searchRange what ActiveClientCode with match case
set fRow to first row index of foundRange
set ClientEmail to value of range ("C" & fRow as text)
set ClientFirstname to value of range ("A" & fRow as text)
(* do something with the foundRange *)
end tell
--Create e-mail
tell application "Mail"
set theMessage to make new outgoing message with properties {visible:true, subject:"Your monthly invoice", content:"Dear " & ClientFirstname & ",
I trust this mail finds you well?
Please find attached your monthly invoice for your immediate consideration.
Regards,
AdminAssist
"}
set message signature of theMessage to signature "Replies & Forwards"
delay 1
tell content of theMessage
make new attachment with properties {file name:"/Users/pienaar0/Documents/AdminAssist/PDF/" & ActiveClientCode & " Sheet1.pdf"}
tell theMessage
make new to recipient at end of to recipients with properties {address:ClientEmail}
end tell
end tell
end tell
end repeat
on MonthAdd(d)
set m to ((month of d as integer) + 1)
set ddd to day of d
if m > 12 then
set m to m - 12
set year of d to (year of d) + 1
end if
if {m} is in {4, 6, 9, 11} and ddd = 31 then --AppleScript treats "Apr 31" as May 1,
set day of d to 30
end if
set month of d to m
if m = 2 and month of d as integer = 3 then --AppleScript treats "Feb 31" as Mar 3,
set day of d to 1 -- Mar 1
set d to d - (1 * days) -- last day of Feb
end if
return d
end MonthAdd

Resources