【问题标题】:Selenium select each div separately that have the same classSelenium 分别选择具有相同类的每个 div
【发布时间】:2018-03-20 16:21:42
【问题描述】:

我试图在 (http://raspored.finki.ukim.mk/Home/Consultations) 中选择所有带有 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更改为2nd、3d等等?

【问题讨论】:

  • 您可能希望使用findElements(复数)方​​法,该方法应返回与选择器匹配的所有元素的集合。然后只需从选择器中删除第 n 个类型,它应该都匹配它们。
  • 我做了,我将添加其余代码。
  • 我不熟悉你使用的语言,但你应该根本不需要driver.findElement(By.cssSelector(".tile-consultation:nth-of-type(x)"))。你为什么做这个?您应该已经拥有 theListOfProfessors 中的所有 Web 元素——您应该对其进行迭代,而不是再次尝试检索 Web 元素。
  • 我不熟悉Java,但我最好的猜测是这样的(伪代码)while theListOfProfessors.hasNext(): WebElement elem = theListOfProfessors.next() ... -- 你已经有了listiterator 对象,theListOfProfessors 你只需要使用它!
  • 很高兴听到@M.T——我已经把它变成了一个答案。如果它对您有用,请考虑接受它作为此问题的答案。

标签: java selenium selenium-firefoxdriver


【解决方案1】:

您已经完成了工作。您已经在这里找到了 web 元素并创建了一个 listiterator:

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)" 那样再次检索元素。您只需要遍历您已经创建的列表迭代器theListOfProfessors。例如。有什么影响

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-02
    • 2022-07-27
    • 1970-01-01
    • 2021-01-02
    • 1970-01-01
    • 2014-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多