Click on safari web page button using AppleScript

2019-05-31 22:24发布

问题:

I'm trying to figure out how to click on the button in a webpage. For example click on the "I'm Feeling Lucky" button in google web page.

This is what I have tried:

tell application "Safari"
    make new document with properties {URL:"https://www.google.com/"}

    do JavaScript "eval(document.getElementById('I'm Feeling Lucky').parentNode.href.substring(11))" in document 1

    delay 1

end tell

But it doesn't work. Any of you knows how can I click on the button using applescript?

I'll really appreciate your help

回答1:

Couple things: Best practice in the safari tell block is to also tell document 1. Also, the ID for that button on Google is wrong. Here's the code from the page:

<button class="gbqfba" aria-label="Google Search" id="gbqfba" name="btnK"><span id="gbqfsa">Google Search</span></button>
<button class="gbqfba" aria-label="I'm Feeling Lucky" onclick="google.x(this,function() {google.ifl &amp;&amp; google.ifl.o();})" id="gbqfbb" name="btnI"><span id="gbqfsb">I'm Feeling Lucky</span></button>

where you can see the ID's for both buttons are 'gbqfba' and 'gbqfbb'. However, clicking them does nothing if nothing is typed in the search box, which then alters the page, and with auto-complete that I have active, the button never needs click. Here's some code for the yahoo.com page which is not dynamic. The search button ID for the search button there is: id="search-submit" …

tell application "Safari"
    activate
    make new document with properties {URL:"https://www.yahoo.com/"}
    delay 2

    tell application "System Events"
        keystroke "stackoverflow"
    end tell
    delay 0.3
    tell document 1
        do JavaScript "document.getElementById('search-submit').click();"
    end tell
end tell

Info on doing the same in Chrome is here: https://stackoverflow.com/a/24644152/3097556