System Events And Safari

I am trying to learn how to use System Events scripting.
The following script puts the text in the search field on www.google.com
But the search engine does not seem to recognize it.
Any pointers to where I’m going wrong with this?

tell application "System Events"
	tell application process "Safari"
		set frontmost to true
		set value of text field 1 of group 6 of UI element 1 of scroll area 1 of group 2 of window "Google" to "England"
		click button "Google Search" of group 6 of UI element 1 of scroll area 1 of group 2 of window "Google"
	end tell
end tell

For Google searching, it’s much easier to just include the search terms in the url replacing any spaces with %20:

set query to "Blue%20Moon"
tell application "Safari"
	activate
	open location "http://www.google.com/search?hl=en&q=" & query
end tell

With a little experimentation, you can get the query language to work for most queries.

To answer your question about GUI Scripting, Enya, you’re really not doing anything wrong. I’m afraid there are still some teething troubles with this technology that remain unresolved.

While waiting for a fix, we have to resort to workarounds. As Adam says, there are other ways to script a Google search. But what if we want to use the technique for some other purpose - such as entering a name and/or password into text fields - to login to a particular website, for example?

One trick that I sometimes use is to simulate a typed entry, using keystrokes. This usually makes the text ‘stick’ rather better than any attempt to change the text field’s value:

tell application "System Events" to tell application process "Safari"
	set frontmost to true
	tell group 6 of UI element 1 of scroll area 1 of group -1 of window "Google"
		set value of text field 1 to ""
		set value of attribute "AXFocused" of text field 1 to true
		keystroke "England"
		click button "Google Search"
	end tell
end tell

Incidentally, you may have noticed that I referred above to group -1 of window “Google”, rather than group 2 of window “Google”. The reason for this is that, if we change Safari’s configuration to show additional elements (such as tabs, the Address Bar or the Bookmarks Bar), they’re inserted as extra groups. So the positive index of our target group, which happens to be the window’s last group (or group -1), is incremented each time (group 3, group 4, etc.)

Counting back from the end just helps to keep a bead on this potentially moving target.