2012-04-05 220 views
1

我使用的是Selenium 2.0 web驅動程序。每當我嘗試在我的頁面中查找某些內容時,我的腳本偶爾會失敗。它會拋出一個異常:Selenium 2.0中定位元素失敗Webdriver

無法找到元素:{「method」:「id」,「selector」:「username」};我的代碼

部分:

driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); 

WebElement userName = driver.findElement(By.id("username")); 
userName.clear(); 
userName.sendKeys("admin"); 

它通過成功有時相同的代碼。我不明白髮生了什麼事。

回答

4

有時會發生這種情況,因爲頁面加載速度比您預期的要慢。我正在通過應用我自己的包裝助手來解決這個問題。它看起來像這樣:

private WebElement foundElement; 

public WebElement find(By by){ 
    for (int milis=0; milis<3000; milis=milis+200){ 
     try{ 
     foundElement = driver.findElement(by); 

     }catch(Exception e){ 
     Thread.sleep(200); 
     } 

    } 
    return foundElement; 
} 

而在後面的代碼:

WebElement userName = find(By.id("username")); 

這種方法將嘗試找到它,如果沒有找到,睡200毫秒,然後再試一次。如果在3秒內沒有找到(可編輯),它會崩潰(你可能不得不說在它的方法拋出一些例外)

我應用它,只要我不知道頁面加載速度有多快...

+0

謝謝。讓我試試你的方法。會讓你知道事情是如何工作的。 – user1315920 2012-04-09 13:26:15

+0

謝謝。有效!! – user1315920 2012-04-20 19:08:40

+0

如果Hari Reddy所示的流暢等待比這種明顯的等待要好的多, – 2014-09-04 11:09:49

3

您的問題,最好的辦法是通過使用WebDriverWait對象使得駕駛者等待在瀏覽器中的id元素的負載,直到 -

new WebDriverWait(driver, 10).until(new ExpectedCondition<Boolean>() { 

     public Boolean apply(WebDriver arg0) { 

      WebElement element = driver.findElement(By.id("username")); 


      return element.isDisplayed(); 
     } 
    }); 

這可以確保駕駛員停止檢查,如果id元素具有加載。如果它在10秒內沒有加載,則會拋出timedOutException。

+0

對於任何可能關注的人:在C#中WebDriverWait對象是Selenium.Support NuGet包的一部分.. – MegaMilivoje 2016-06-04 18:10:56

相關問題