列表<WebElement>返回空列表



我正在尝试循环列表并将项目存储在另一个列表中以比较数据,但我的列表没有迭代,

这是我的实现

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<>();

你应该像这样定义一个web元素列表

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;
}

最新更新