[英]List<WebElement> returns empty List
我试图遍历一个 List 并将项目存储在另一个 List 中以比较数据,但我的 List 没有被迭代,
这是我的实现
private final By listNotificationType = By.xpath("//*[@id='a24687a9017f']//p/text()");
public List<WebElement> verifyListNotificationType()
{
List<WebElement> drpdwnData = new ArrayList<>();
for(WebElement a: driver.findElements(listNotificationType))
{
drpdwnData.add(a);
}
return drpdwnData;
}
String[] arrNotifications = { "Abc", "Xyz", "Def" };
List<Object> listNotifications = Arrays.asList(arrNotifications);
MyPage myPage = new MyPage();
System.out.println("Final Data:: "+myPage.verifyListNotificationType());
Assertions.assertThat(listNotifications).hasSameElementsAs(myPage.verifyListNotificationType());
当我执行代码时会发生什么我得到了结果Final Data:: []
有人可以告诉我为什么列表返回空,我的 xpath 在我重新检查时是准确的,但我仍然无法迭代它,而调试 for 循环甚至没有被执行。 我不确定我哪里出错了。
代替
List<WebElement> drpdwnData = new ArrayList<>();
你应该像这样定义 WebElement 列表
List<WebElement> drpdwnData = new ArrayList<WebElement>();
此外,我们不需要;
for for 循环声明。 请看这一行:
for(WebElement a: driver.findElements(listNotificationType));
我还建议不要在 XPath 中使用text()
。 相反,请尝试使用以下代码。
您还应该在迭代之前放置一个if条件,如果列表的大小>0
则进入for循环,否则不要进入循环。 通过这种方式,您将获得一些优化的代码。
代码:
private final By listNotificationType = By.xpath("//*[@id='a24687a9017f']//p");
public List<WebElement> verifyListNotificationType()
{
List<WebElement> drpdwnData = new ArrayList<WebElement>();
List<WebElement> actualList = driver.findElements(listNotificationType);
if (actualList.size() > 0) {
System.out.println("actualList does have at least one web element, So Bot will go inside loop.");
for(WebElement a : actualList)
drpdwnData.add(a);
}
else
System.out.println("actualList does not have any web element, So Bot will not go inside loop.");
return drpdwnData;
}
在循环开始之前捕获WebelEments
。
当我重新检查它时,我的 xpath 是准确的,但我仍然无法对其进行迭代,而调试 for 循环甚至没有被执行。
可能会返回0
元素,因此请使用一些等待语句。
private final By listNotificationType = By.xpath("//*[@id='a24687a9017f']//p");
WebDriverWait wait = new WebDriverWait(driver, 20);
List<WebElement> actualList = wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(listNotificationType));
public List<WebElement> verifyListNotificationType() {
List<WebElement> drpdwnData = new ArrayList<>();
for (WebElement a : actualList) {
drpdwnData.add(a);
}
return drpdwnData;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.