替换 'Thread.sleep(5000)' 的替代方法

Alternative way to replace 'Thread.sleep(5000)'

是否有其他方法可以替代 'Thread.sleep(5000)'?目前,commentsbutton 只点击一次,然后会继续到 repliesbutton 的代码,即使还有其他 commentsbutton 元素?所以我认为可能是因为 'Thread.sleep(5000)' 页面未完成加载。

          if(commentsbutton.size() > 0) {
                commentsbutton.get(0).click(); //click on button if found
                Thread.sleep(5000); //pause for 5 seconds
          }           
          else clickMore = false;

          if(repliesbutton.size() > 0) {
                 repliesbutton.get(0).click(); //click on button if found
                 Thread.sleep(5000); //pause for 5 seconds
           }
           else clickMore = false; 

           if(seemorebutton.size() > 0) {
                  seemorebutton.get(0).click(); //click on button if found
                  Thread.sleep(5000); //pause for 5 seconds
           }
           else clickMore = false;
           }

您可以为此使用循环,但您必须了解,此循环将在执行期间使用进程资源。我认为,Thread.sleep 无论如何都适合您的情况...

long now = System.currentMillisec();   
long executionDuration = now + 5000;
while(now < executionDuration){
    now = System.currentMillisec();
}

但正如你所说

the commentsbutton only clicks once and will move on to the codes

看来,您需要在 commentsbutton 集合的元素上添加额外的循环,以便在转到回复按钮之前单击您拥有的所有评论按钮。现在你只点击一个按钮,你得到 commentsbutton.get(0).click();

if(commentsbutton.size() > 0) {
    for (WebElement element : commentsbutton) {
        element.click(); //click on button if found
        Thread.sleep(5000); //pause for 5 seconds
    }
}