[英]Clicking All Buttons with Javascript on a Dynamically Loaded Page
我正在嘗試編寫一個 javascript 代碼,單擊https://www.teamblind.com/上討論線程中的所有按鈕,這樣我就可以看到所有評論,而無需單擊按鈕展開它們。
我發現我可以通過執行以下操作來單擊所有按鈕
var bs = document.getElementsByClassName('btn_more');
bs[0].click();
在控制台中,我只需要重復運行 bs[0].click(); 直到剩下一個元素,但是當我將其變成如下所示的 while 循環時
function clickall() {
var bs = document.getElementsByClassName('btn_more');
while (bs.length > 1 ) { // 1 because the last button directs to other page, all other buttons expands the contents in the current thread
bs[0].click();
}
return;
}
當我在 Web 控制台中運行此功能時,瀏覽器選項卡實際上會停止工作,我不得不使用任務管理器關閉瀏覽器進程以停止在控制台中運行此功能。
我的猜測之一是頁面動態加載,也許我需要等待頁面展開? 有誰知道為什么選項卡可以掛起運行這樣的功能以及應該如何修復?
記錄bs
大小
點擊后 btn 本身可能不會被刪除,它可能變得不可見。 除此之外,按鈕在循環之前已經被收集,所以如果它們被刪除,這可能是導致錯誤的原因,無法找到的節點正在應用函數。 因此for...each
在 while 循環內使用for...each
循環或查詢元素。
所以首先不需要while循環。 讓我們用if
來做:
function clickall() {
var bs = document.getElementsByClassName('btn_more');
// 1 because the last button directs to other page,
// all other buttons expands the contents in the current thread
if ( bs.length > 1 ) {
bs[0].click();
}
}
所以我們只點擊一次這個按鈕。 現在我們可以定期運行該代碼:
// You can stop the loop with window.clearInterval(intervalHandle); when you want.
let intervalHandle = window.setInterval(clickall, 500);
進一步閱讀:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.