我試圖遍歷一個 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 回圈甚至沒有被執行。我不確定我哪里出錯了。
uj5u.com熱心網友回復:
代替
List<WebElement> drpdwnData = new ArrayList<>();
你應該像這樣定義 WebElement 串列
List<WebElement> drpdwnData = new ArrayList<WebElement>();
此外,我們不需要;for 回圈宣告。請看這一行:
for(WebElement a: driver.findElements(listNotificationType));
我還建議不要text()在 XPath 中使用。相反,請嘗試使用以下代碼。
您還應該在迭代之前放置一個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;
}
uj5u.com熱心網友回復:
捕獲WebelEmentsbefore 回圈開始。
當我重新檢查它時,我的 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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/332961.html
下一篇:從串列中洗掉和移除一個指標
