AppleScript& Javascript:从HTML行获取所有数据

时间:2017-02-28 10:30:44

标签: javascript class google-chrome applescript

我想从一个网站获取所有号码,这些号码在同一行。

所有人都有相同的类:

<td class="sortable dsNumberId">

                                    10999694994

                            </td>

我想将其返回到剪贴板并得到如下结果:

  

10999694994

     

10949644992

     

10959594991

     

109796976

要收集的值的数量是随机的,它可以是2到100,第一个类=&#34;可排序的dsNumberId&#34;实际上是无效的(只是带有链接的标题)

我在这里有这个脚本:

tell application "Google Chrome"
    tell tab 2 of window 1 to set DSIDsList to execute javascript "var outPut=[0]; var arr=document.getElementsByClassName('sortable dsPersonId');for (var i in arr) {outPut.push(arr[i].innerHTML)};outPut;"

end tell

这个问题最后给了我一个文字&#34; &#34;,缺失值,缺失值,缺失值}&#34;

并在开头给我一个我不需要的无效标题/网址。

1 个答案:

答案 0 :(得分:1)

tell application "Google Chrome"
    tell tab 1 of window 1 to set DSIDsList to execute javascript "
    var outPut=[]; 
    var arr=document.querySelectorAll('.dsNumberId');
    for (var i=0; i < arr.length; i++) {
        if(arr[i].innerHTML !== ''){
            outPut.push(arr[i].innerHTML.trim())
        }
    };
    outPut;"
end tell

将搜索更改为使用document.querySelectorAll,这样您就可以定位单个类名,例如dsNumberId。 (另请注意,当您的示例HTML指定为dsPersonId时,您的脚本正在寻找dsNumberId。)我还添加了trim()以从返回的结果中删除额外的空格。

鉴于此HTML(请注意原始帖子中的额外空格),

<html>
<body>
<table>
<td class="sortable dsNumberId">

                        20

                </td>
                <td class="sortable dsNumberId">

                        30

                </td>
                <td class="sortable dsNumberId">

                        40

                </td>
                <td class="sortable dsNumberId">

                        50

                </td>
                <td class="sortable dsNumberId">

                        60

                </td>
                <td class="sortable dsNumberId">

                        70

                </td>
                </table>
                </body>
                </html>

修改后的脚本将返回

{"20", "30", "40", "50", "60", "70"}