Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

NotSponsored

macrumors newbie
Original poster
May 1, 2015
2
0
G'day.

1. I've managed to programatically fill the find field (command f) of a Safari page - but I have no clue how to obtain/read the results of it.

Essentially, I want to search for a string. If result>0 … do this, else.. do nothing.

I did attempt to use Source of Document but it kept returning 'cannot read source' error

Any suggestions?

2. I have a script which loops about every 20 or 30 seconds (using Delay and Return) and sometimes it times out - how can such an error be avoided?

TIA.
 
This works for me:

Code:
tell application "System Events"
	get value of text field 1 of group 2 of group 3 of window 1 of application process "Safari"
end tell

The only caveat is that this hierarchy is subject to change on a whim with a software update. I could show you how to walk the UI hierarchy if you don't know how.
 
Personally, I'll use UI scripting as an absolute last resort. It tends to be slow, fiddly and a bit unpredictable in my experience. Still, there are situations where you have no choice.

In this case, you don't really need to use Safari at all. You could do something like this:

Code:
--the url to scan
set theURL to "https://www.macrumors.com"

--the text to look for
set theSearchString to "Watch"



--user curl to get the source code
set theSourceCode to do shell script ("curl " & theURL)

--find out how many characters into the source code the search string first appears
set theOffset to offset of theSearchString in theSourceCode

if theOffset > 0 then
	display alert "Success!" message "The text '" & theSearchString & "' was found in the source code."
else
	display alert "Failure!" message "The text '" & theSearchString & "' was not found in the source code."
	
end if


Don't fall into the trap of thinking that scripting is about mimicking user actions (clicks, keypresses etc) in the GUI.

Hope that's of some help!
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.