Click on safari web page button using AppleScript

二次信任 提交于 2019-12-08 04:28:27

问题


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



来源:https://stackoverflow.com/questions/24917282/click-on-safari-web-page-button-using-applescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!