[英]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.