我有一个网页,其中一个元素具有唯一 ID“SomeID”
当使用“findElement”方法搜索单个元素时,它会找到该元素。
WebElement element = webDriver.findElement(By.id(SomeID))
当使用搜索多个元素的方法时,我得到一个 0 的数组
List<WebElement> elements = webDriver.findElements(By.id(SomeID));
我不明白为什么它找不到带有“findElements”的元素。
是因为每个容器的“id”应该是唯一的吗?
“findElements”是否适用于其他类型的搜索(xpath 等)?
谢谢
最佳答案
定位器 By.id
将始终返回单个元素,即使存在多个元素也是如此。这可能是因为 W3C 标准规定 id
必须是唯一的,但浏览器并未强制执行。
要获取具有相同 id 的所有元素,请使用 By.cssSelector
并在 id
属性上设置条件:
List<WebElement> elements = webDriver.findElements(By.cssSelector("[id='some-id']"));
请注意,您可能遇到了时间问题。在这种情况下使用服务员:
List<WebElement> elements = WebDriverWait(driver, 10)
.until(EC.presenceOfAllElementsLocatedBy(By.cssSelector("[id='some-id']")));
关于java - 为什么在搜索多个元素时无法在 Selenium 中按 id 找到一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40287685/