2015-10-28 150 views
-3

我试图循环for循环7次,其中webelement会点击只有7次。即使网页中还有其他commentsbutton元素,循环也会忽略它们并停止点击。for循环的点击网页元素

目前,该脚本将仍然点击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); 
    //} 
} 
+0

你必须找到下一个元素每次迭代? –

+0

@AndrewPiliser我只需要找到这个相同的元素7次,并忽略其他人如果有超过7个这些元素。 –

+0

当页面打开时,您的页面是否包含7个或更多commentsButton?或者在点击第一个评论按钮后出现第二个评论按钮? – Sighil

回答

0

试试这个:

WebDriverWait wait = new WebDriverWait(driver, 10); 

for(int i=0; i<7; i++) { 
    WebElement element = wait.until(
     ExpectedConditions.visibilityOfElementLocated(
      By.xpath("//button[@class='-cx-PRIVATE-PostInfo__commentsLoadMoreButtonEnabled']"))); 

    driver.findElement(By.xpath("//button[@class='-cx-PRIVATE-PostInfo__commentsLoadMoreButtonEnabled']")).click(); 
} 

说明:按下面的评论,你提到你其实想点击load more comments按钮上的Instagram post整整7倍。所以,如果你观察网页的HTML,特别是按钮的,就是:

<button class="-cx-PRIVATE-PostInfo__commentsLoadMoreButton -cx-PRIVATE-PostInfo__commentsLoadMoreButtonEnabled"> 

但是,一旦你点击按钮,该网站开始获取更要显示的评论。在此期间,类名值-cx-PRIVATE-PostInfo__commentsLoadMoreButtonEnabled被删除的HTML变成这样:

<button class="-cx-PRIVATE-PostInfo__commentsLoadMoreButton" disabled="true"> 

一旦获取数据并显示它,这是除去重新添加类名值和按钮被启用。

因此,如果你想多次点击按钮加载全部或大部分评论,你将不得不使用waits和循环的组合。您正在使用Thread.sleep()进行暂停,然后单击该按钮。但是使用等待是一个更好的选择,因为它轮询DOM以查找该时间段内的元素,并且一旦它满足预期条件(在这种情况下元素的可见性),然后继续执行下一行的代码。

+0

我添加了'List '给commentsbutton7和**“Exception in thread”main“java.lang.IndexOutOfBoundsException:toIndex = 6”的错误** ** –

+0

@dark_space - 尝试打印列表的长度。 'commentsbutton.size()'。我认为它取得的不到7个元素。如果是这样,那么你需要检查你的xPath。 – JRodDynamite

+0

尝试打印列表长度,但仍具有相同的** IndexOutOfBoundsException **错误,并且没有打印出来。 –