用于单击web元素的For循环

时间:2015-10-28 08:39:32

标签: java selenium for-loop

我正在尝试循环for循环7次,其中webelement将仅被点击7次。即使网页中还有其他commentsbutton元素,循环也会忽略它们并停止点击。

目前,该脚本仍然会不停地点击webelement。

 WebElement commentsbutton = (WebElement) comment.findElement(By.xpath("//button[contains(@class,'-cx-PRIVATE-PostInfo__commentsLoadMoreButton -cx-PRIVATE-PostInfo__commentsLoadMoreButtonEnabled')]")); //view all/ load more comments

//click more comments
for(int i = 0; i < 7; i++) {
    //for (WebElement comments_element : commentsbutton) {
    commentsbutton.click(); //click on button if found
    Thread.sleep(3000); //pause for 5 seconds   
    System.out.println(commentsbutton);
    //}
}

1 个答案:

答案 0 :(得分:0)

试试这个:

load more comments

说明:根据以下评论,您提到您确实想要点击Instagram post上的<button class="-cx-PRIVATE-PostInfo__commentsLoadMoreButton -cx-PRIVATE-PostInfo__commentsLoadMoreButtonEnabled"> 按钮7次。因此,如果您观察到页面的HTML,特别是按钮的HTML,则为:

-cx-PRIVATE-PostInfo__commentsLoadMoreButtonEnabled

但是,一旦您单击该按钮,该站点就会开始提取更多要显示的注释。在此期间,类名称值<button class="-cx-PRIVATE-PostInfo__commentsLoadMoreButton" disabled="true"> 将被删除,HTML将变为:

Thread.sleep()

获取数据并显示后,将删除已删除的类名值,并启用该按钮。

因此,如果您想多次单击该按钮以加载所有或大部分注释,则必须使用waits和循环的组合。您使用$date = new DateTime("oct 27 2015 11:11:22:933");暂停,然后点击按钮。但是然后使用等待是一个更好的选择,因为它轮询DOM以找到该段时间的元素,并且一旦满足预期条件(在这种情况下是元素的可见性),它就会继续执行下一行代码。