Selenium分别选择具有相同类

时间:2018-03-20 16:21:42

标签: java selenium selenium-firefoxdriver

我试图在(http://raspored.finki.ukim.mk/Home/Consultations)中选择所有div withclass tile-consultation,点击每个div并从每个div中提取一些数据,我尝试使用:

    List<WebElement> professors = driver.findElements(By.className("tile-consultation"));
    ListIterator<WebElement> theListOfProfessors = professors.listIterator();
    Thread.sleep(1000);

    int i = 1;
    while(theListOfProfessors.hasNext()) {
        WebElement professorI = driver.findElement(By.cssSelector(".tile-consultation:nth-of-type(2)"));
        professorI.click();

        Thread.sleep(1000);
        close = driver.findElement(By.cssSelector("button.btn-close"));
        close.click();
        Thread.sleep(1000);
     }

但是如何在while循环中将1更改为2,3d等等?

1 个答案:

答案 0 :(得分:4)

你已经完成了工作。您已经找到了网络元素并在此处成为了一个列表项目:

List<WebElement> professors = driver.findElements(By.className("tile-consultation"));
ListIterator<WebElement> theListOfProfessors = professors.listIterator();

findElements方法将返回与选择器匹配的元素集合。您无需再次检索元素,就像您尝试在该循环中使用driver.findElement(By.cssSelector(".tile-consultation:nth-of-type(x)"一样。您只需要遍历已创建的listiterator theListOfProfessors。例如。

的影响
while(theListOfProfessors.hasNext()) {
    WebElement elem = theListOfProfessors.next()
    // do something with elem
}