I am new to applescript. I want to save a cvs or text file that contain each line that start with HFLS from a specific webpage
here is what I have:
Thank your for your hep.
tell application "Safari"
activate
set theURL to URL of front document
set selectedText to the text of document 1
set theDate to do shell script "date +'%d-%m-%Y'"
set Names to paragraphs of selectedText
repeat with nextLine in Names
if length of nextLine is greater than 0 then
if nextLine starts with "HFLS" then
display alert nextLine
set the clipboard to nextLine
end if
end if
end repeat
end tell
I just found out the solution, Thank you.
You are welcome to improve the code
set myFile to open for access (choose file name) with write permission
tell application "Safari"
activate
set theURL to URL of front document
set selectedText to the text of document 1
set theDate to do shell script "date +'%d-%m-%Y'"
set Names to paragraphs of selectedText
repeat with nextLine in Names
if length of nextLine is greater than 0 then
if nextLine starts with "HFLS" then
display alert nextLine
set the clipboard to nextLine
write nextLine & linefeed to myFile
end if
end if
end repeat
end tell
close access myFile
actually theDate, theURL and the clipboard is not used at all in the script
I recommend also to add some error handling to open and close the file reliably
set myFile to (choose file name)
try
tell application "Safari" to set Names to paragraphs of text of document 1
set fileRef to open for access myFile with write permission
repeat with nextLine in Names
if nextLine starts with "HFLS" then
display alert nextLine
write nextLine & linefeed to fileRef
end if
end repeat
close access fileRef
on error
try
close myFile
end try
end try
I’d actually use the Satimage.osax to do this job. (It adds regular expressions and other goodies to AppleScript.)
But even without it I’d still rather use regex.
set foundText to do shell script “osascript -e ‘tell application "Safari" to return text of front document’ \
| sed -En -e ‘/^[[:blank:]]*$/d’ -e ‘/^HFLS/{n;p;}’”
Once you have the text you can write it to your file in one go.