首页 > 解决方案 > 如何在selenium javascript中遍历具有特定类名的元素

问题描述

页面上有动态数量的 div 容器,类名为“海绵”,我需要遍历这些容器,然后从每个容器中获取详细信息,但我不知道该怎么做。这是我到目前为止尝试过的......

const containers = await driver.findElements(By.className(`sponge`))

for(let t = 0; t < containers.length; t++){
  let runner = await containers[t].findElement(By.xpath(`//div[2]/div[1]/div/p`)).getText()
  console.log(runner)
}

当我这样做时,我只是在第一个“海绵”类容器中获得“跑步者”x 次,其中 x 是“容器”的长度。它实际上并没有找到我想要的容器中的“跑步者”

标签: javascriptseleniumxpathwebdriver

解决方案


要立即child node获得parent node您需要使用的立即.尝试。

const containers = await driver.findElements(By.className("sponge"))

for(let t = 0; t < containers.length; t++){
  let runner = await containers[t].findElement(By.xpath(".//div[2]/div[1]/div/p")).getText()
  console.log(runner)
}

推荐阅读