2013-06-18 141 views
0

怎麼說,我得到IndexOutOfBoundsException同時使用Java增強的for循環?我的代碼看起來像這樣Java增強for循環和IndexOutOfBoundsException?

for (WebElement input : driver.findElements(By.cssSelector("input[type='text']"))) { 
    if (input.isDisplayed()) { 
     input.clear(); 
    } 
} 

它使用硒的webdriver找到所有<input type="text" />標籤和明確表示,他們的內容是否會顯示(否則它會拋出一個不同的例外)。並在一些測試中,我得到

java.lang.IndexOutOfBoundsException: Index: 1, Size: 0 
    at java.util.ArrayList.rangeCheck(ArrayList.java:604) 
    at java.util.ArrayList.get(ArrayList.java:382) 

其餘的堆棧跟蹤Pastebin

編輯

即使我添加了檢查數組空虛

List<WebElement> inputs = driver.findElements(By.cssSelector("input[type='text']")); 
if (!inputs.isEmpty()) { 
    for(WebElement input : inputs) { 
    } 
} 
+1

'driver.findElements()'返回的'Iterator'有嚴重錯誤。 – EJP

+0

我有點想通了,但仍然 - 我應該如何妥善處理這種情況? –

+0

你可能運行的是舊版本的Selenium? – Arran

回答

0

您可以檢查此聲明driver.findElements(By.cssSelector("input[type='text']"))的結果,這個錯誤仍然存​​在。

看來driver.findElement即使在增強環路開始執行之前,s也正在獲取indexOutOfBound異常。你可以嘗試調試或打印控制檯上的值。

1
java.lang.IndexOutOfBoundsException: Index: 1, Size: 0 

這指定你已經進入了循環,在索引1處,儘管數組的大小是0.你應該在索引0處輸入。這很奇怪。因此,這將表明,錯誤被拋出由見下文


嘗試運行一些調試 - 在此之前,嘗試和打印的由

driver.findElements(By.cssSelector("input[type='text']")) 

返回的對象,並嘗試看看是否有什麼實際返回。

我會評論,但沒有足夠的代表。

此外它是一個for-each循環。