How to click a button on a Web Page with AppleScript

Now that you know how to make Safari visit a web page using AppleScript, you will probably want to take your automation to the next level by being able to interact with that page! For this tutorial I am going to teach you how automate clicking on almost anything on almost any web page.

There are a few different ways you can make Apple script click a button in Safari. Which method you choose depends on how the code of the webpage you are working with.

Step 1: Figure out which method you need to use…
First you have to open up another browser like Firefox or Chrome. I find that these are the easiest to use when trying to inspect different elements on a web page. In this case, we will take a look at a search for sporks on Google. Our goal is to click the “More” button on the menu.

Using Chrome, right click on the element that you are trying to click using applescript.

Then select the inspect element tab.

Screen Shot 2014-12-08 at 5.15.49 PM

 

This will bring up a box at the bottom of the screen with a whole bunch of code.

Screen Shot 2014-12-08 at 5.16.35 PM

Now you have to inspect the code… we are looking for something that says either id, name, or class. If none of these things exist, don’t worry, there is one last thing you can try.

Screen Shot 2014-12-08 at 5.17.09 PM

The best case scenario that you can hope for is if inside of the element there is something that says “id”. In this case there is something that says,  id =”htb_more”

Clicking an HTML Element by ID with AppleScript

The code to find an element by ID and then click on it is as follows:

First paste this into the top of your AppleScript document

to clickID(theId) --creates a function that we can use over and over again instead of writing this code over and over again

tell application "Safari" -- lets AppleScript know what program to controll

do JavaScript "document.getElementById('" & theId & "').click();" in document 1 -- performs JavaScript code that clicks on the element of a specific id

end tell -- tells Applescript you are done talking to Safari

end clickID -- lets AppleScript know we are done with the function

 

Now when you would like to click on something on a web page, lets say its the “More” button on Google,  you can insert this  anywhere in your code.

clickID("htb_more")

 

Clicking an HTML Element by Name with AppleScript

 

Lets say that there is nothing that says “id”, the next best thing is to find a something that says “name”. For this example we are looking to click the search button on Google. Lets inspect the element just like before to find out what we need to do next!

 

 

Screen Shot 2014-12-08 at 5.29.13 PM

 

It looks like we found something that says name=”btnG”…

Screen Shot 2014-12-08 at 5.32.04 PM

To use this info to click that search button type this into the top of your AppleScript code…

to clickName(theName, elementnum)

tell application "Safari"

do JavaScript "document.getElementsByName('" & theName & "')[" & elementnum & "].click();" in document 1

end tell

end clickName

Now when you would like to click on something on a web page, like the search button on Google,  you can insert this  anywhere in your code.

clickName(“btnG”, 0)

Now, usually this will work, especially if there is only 1 thing on the page with the name=”btnG”, however if there are multiple elements with name=”btnG” you will have to do a bit more work.

You might have noticed that this code, clickName(“btnG”,0) , has a little more to it than the previous clickID statement. That is because on a web page there can only be 1 specific element with 1 specific ID. This makes it easy for us to identify elements with ids. When trying to identify an element by name or class we have to specify which instance on the page we are talking about.

For example… There could be 10 search buttons on the page, and they could all have the name=”btnG” inside of them. Because of this we have to tell Applescript which element with the name “btnG” we want to click on.

clickName("btnG", 0) --would click the first element with name "btnG"

clickName("btnG", 1) --would click the second element with name "btnG"

clickName("btnG", 2) --would click the third element with name "btnG"

etc…

For name, you will most likey only need to use clickName(“theName”, 0)… but when trying to click on something by Class or by Tag you will have to play around with what number works…

Clicking an HTML Element by Class with AppleScript

Clicking an element by class is the same as clicking an element by name in practice.

Screen Shot 2014-12-08 at 5.32.04 PM

Lets take the above example of clicking on the search button again…

Here we see <button class=”gbqfb”……

We can take this class “gbqfb” and now insert it into our slieghtly modified code for clicking on an element by class.

to clickClassName(theClassName, elementnum)

tell application "Safari"

do JavaScript "document.getElementsByClassName('" & theClassName & "')[" & elementnum & "].click();" in document 1

end tell

end clickClassName

 

The major difference in the code here is this… “document.getElementsByClassName” here instead of the “getElementsByName” function we are using “getElementsByClassName”

Now, to utilize this just paste below anywhere in your code:

clickClassName("gbqfb", 0)

Clicking an HTML Element by Tag Name with AppleScript

Lets say, worst case scenario you come across something that you need to click and there is nothing inside the code for you to use! For example, if the code reads simply

<button>Search</button>

The only thing that we have to identify what we need to click on here is what is called the Tag.

To click on the tag do the same as above for Name and Class, however use the following slightly altered code:

 

to clicktagName(thetagName, elementnum)

tell application "Safari"

do JavaScript "document.getElementsByTagName('" & thetagName & "')[" & elementnum & "].click();" in document 1

end tell

end clicktagName

This code searches the document for any elements, like <button>, <li>, or anything else inside of  <>, and then tells Safari to click it.

To utilize clicking by tag name just paste the following into your AppleScript:

clicktagName(“button”, 0)

NOTE: This will not work if it is already inside of a Safari Tell Statement.

 

Will work:

 

tell application "Safari"
 --some code...
 end tell

clickID("htb_more")

tell application "Safari"
 --some code...
 end tell

 

Will Not Work:

 

tell application "Safari"
 clickID("htb_more")
 end tell

 

24 Responses to “How to click a button on a Web Page with AppleScript

  • This is great, thanks Kindly.
    Do you know how to tell is the button click was succesful?

    I’m writing a script to click on on a class, but sometimes those links are missing and I want to click on something else instead.

    Can we return a value if the class exists? and look for another class if now.

    Thanks!

    • Hmm great question it depends on what you are trying to do.

      One way is that you can use a try statement to see if the next actions in your script are working after the button click. Without an example its hard to really give you an good solution. I’m shooting you an email to get more info.

  • Is there a way to click a button according to a class’s innerhtml? Sorry if that’s not clear, I’m just now learning.

    Example.

    reorder

    If I have multiple buttons on the page and the number of buttons varies depending on other factors, then can i specify according to the text “reorder”?

    • Looks like my example got corrupted so I’ll try another example.
      http://cubemg.com/wp-content/uploads/2014/12/Screen-Shot-2014-12-08-at-5.17.09-PM.png
      In the above screenshot, if we have multiple buttons with a span class “mn-hd-txt”, would it be possible to designate that I am referring to the one that includes the text “more”.

    • That is funny, I was actually working on that a few weeks ago…. try this

      ————————————————————
      — the following is a sample for https://newyork.craigslist.org
      ————————————————————

      to getInputByClass(theClass, num) — defines a function with two inputs, theClass and num
      tell application “Safari” –tells AS that we are going to use Safari
      set input to do JavaScript ”
      document.getElementsByClassName(‘” & theClass & “‘)[” & num & “].innerHTML;” in document 1 — uses JavaScript to set the variable input to the information we want
      end tell
      return input –tells the function to return the value of the variable input
      end getInputByClass

      to clickClass(theClass, num) — defines a function with two inputs, theClass and num
      tell application “Safari” –tells AS that we are going to use Safari
      set input to do JavaScript ”
      document.getElementsByClassName(‘” & theClass & “‘)[” & num & “].click();” in document 1 — uses JavaScript to set the variable input to the information we want
      end tell
      end clickClass

      set x to 0 — start number
      set className to “txt” — name of class
      set searchTerm to “antiques” — something in the inner HTML

      repeat 1000 times — how many time you want to repeat this

      set trialInnerHTML to getInputByClass(className, x) — pulls content from each class with search term

      if searchTerm is in trialInnerHTML then
      clickClass(className, x)
      exit repeat
      end if

      set x to x + 1 — goes to the nextclass

      end repeat

      • Geno De Rozario
        5 months ago

        Hi Samuel, this always returns missing value, any help would be greatly appreciated.

        • sam@cubemg.com
          5 months ago

          Because you are not getting any value there is nothing to return. A missing value is correct. However, when you perform the script it should click something.

  • I have a search field that only registers that dosnt use a button to trigger the search function, and insted requires the return key. Is it possible to to use Javascript to automate the return key function?

    onkeypress=”return isSpaceKey(event);”

    • well… you can do a few things. If you can find the name of the form that needs to be submitted you can do this:

      tell application “Safari”
      do JavaScript ”
      document.getElementById(‘searchform’).submit();” in document 1 — change “searchform” to be the id of the form
      end tell

      You could also click the element first using JS, then use the system events to simulate hitting enter on your keyboard like this:

      tell application “Safari”
      activate
      delay 3
      tell application “System Events”
      key code 76
      end tell

      end tell

      Let me know if this works for you!

  • Hi Samuel, I’m enjoying your instructions and look forward to using Applescripts to automate some of MY daily activities.

    I tried this and another of your tutorials, and I’m having the same problem each time.

    When I try to run the script I get this error:

    error “Safari got an error: Can’t get document 1.” number -1728 from document 1

    Seems like a simple Problem, but non of your other comments or posts talk about it.

    Thanks

  • Hi Samuel, Michael again.

    Earlier I mentioned that quotes on this page cause runtime errors when the code is copied from this site over to an editor. I wanted to add that line comments – double hyphens – don’t copy correctly, either.

    Best,

    Michael

    • Ah thanks for that Michael, I need to update the site when I have time to have the code properly formatted. Sorry for the inconvenience.

  • Hi Samuel
    Your tutorials have been real helpful.
    Do you have a code for shecking a checkbox on a website?

    Phill

    • Hey Phil,

      It is the same concept, you just have to find the ID, class, tag # etc…

  • Can someone tell me how to make this work. My button is tricky.

    I’ve tried multiple things and I cannot get the button to click to save my life. i have to enter about 1000 asset tags into a database and if i the automator combined with the this button pushing script i can have my computer do it all alone. I just cannot get it to pushing the button.

  • firefly
    1 year ago

    Hi,
    Been trying to have my applescript click on this button in a web page, but for some reason, not working. Note that, there are several areas on the page. I don’t know if I have to point to that specific frame.

    type=”button” class=”primary-navbar-link” id=”logoutBtn” title=”Log Out” onclick=”LogOffSystem()”>

    i tried with Id, title and class, but for some reason it doesn’t do the job.

    tell application “Safari”
    activate
    tell document 1
    do JavaScript “document.getElementsByClass(‘primary-navbar-link’).click();”
    end tell
    end tell

    Thanks

    • sam@cubemg.com
      1 year ago

      Hey there firefly, if you are trying to click by class you are missing the instance number. You would need to write:
      document.getElementsByClass(‘primary-navbar-link’)[0].click();

      Notice the [] with the 0 will click I the first link with that class, 1 will click on the 2nd etc…

      • firefly
        1 year ago

        Thanks for the quick reply.
        I added the [0] and tried from 0-6 (i have 6 instances on the page), but still not success. I tried again with the id (2 id with the same name), without success.
        do JavaScript “document.getElementsByid(‘logoutBtn’)[1].click();”

        Any idea where to look next ?

        • sam@cubemg.com
          1 year ago

          The code you are working with isn’t correct. For ID there is only one of those on the page. You are confusing id and class in your javascript.
          For ID:

          tell application “safari”
          do JavaScript “document.getElementById(‘logoutBtn’).click();” in document 1
          end tell

  • Fantastic! Works like a charm. Thank you!

  • Sorry to revive an old post but I’ve been trying to get one of the above options to click on the “accept and connect” button on the following page,

    http://cportal-http.colonynetworks.com/portal/ctc/index.php?COLONYSESSID=m2a3o2d0mopukc06k2uj81ap22&LANG=en

    but nothing I’ve tried has worked so far. Any help would be greatly appreciated.

    Thanks.

    • sam@cubemg.com
      1 month ago

      Hi There JJ,
      Try using: clickClassName("form-submit-button", 0)
      Let me know how that works for you.

Leave a Reply

Your email address will not be published. Required fields are marked *