2016-12-02 94 views
1

在我們對任何Web元素執行操作以避免「NoSuchElementException」異常之前,我已經經歷了許多Google答案,以確保如何確保元素可用性。Selenium WebDriver:如何確保Web頁面上的元素可用性?

  1. WebDriver driver = new FirefoxDriver();
  2. driver.findElement(By.id(「userid」))。sendKeys(「XUser」);

這裏線#2會拋出「」 NoSuchElementException異常」,如果該元素沒有可用的頁面上。

我只是想避免這種異常被拋出。

有可用多種方法檢查這webdriver的。

  1. isDisplayed()
  2. 的IsEnabled()
  3. driver.findElements(By.id(「userid」))。size()!= 0
  4. driver.findElement(By.id(「userid」))。size()!= null
  5. driver.getPageSource ().contains(「userid」)

這是上述方法中確保元素可用性的最佳方法之一?爲什麼?

除此之外還有其他方法嗎?

在此先感謝。感謝您寶貴的時間。

回答

0

嘗試使用顯式的等待selenium API。

等待一段時間,直到您所需的元素在網頁上可用。你可以試試下面的例子:

WebDriverWait wait = new WebDriverWait(driver,10); 
wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.id("userid")))); 

所以上面的行會等待直到元素10秒,如果在不到10秒鐘的可用元素,則其將停止等待,繼續向前邁進執行。

1
public boolean isElementPresentById(String targetId) { 

     boolean flag = true; 
     try { 
      webDrv.findElement(By.id(targetId)); 

     } catch(Exception e) { 
      flag = false; 
     } 
     return flag; 
    } 
  • 如果元素是可用的,你會得到真正的從一個方法否則爲false。
  • 所以,如果你得到錯誤,那麼你可以避免點擊該元素。
  • 您可以使用上面的代碼確認元素的可用性。
0

您可以使用您的問題中列出的任何方法 - 沒有最好的或最差的方法。

還有一些其他方法 - 兩個由@Eby和@Umang在他們的答案中提出,以及下面的方法不等待元素,只是在這個元素存在或不存在的時候勉強:

if(driver.findElements(By.id("userid")).count > 0){ 
     System.out.println("This element is available on the page"); 
    } 
    else{ 
     System.out.println("This element is not available on the page"); 
    } 

然而一個要求是::

線#2會拋出「」 NoSuchElementException異常」,如果元素不 可用的頁面上。
我只想避免這種異常被拋出

然後在我看來,最簡單的方法是:

try{ 
    driver.findElement(By.id("userid")).sendKeys("XUser"); 
}catch(NoSuchElementException e){ 
    System.out.println("This element is not available on the page"); 
    -- do some other actions 
} 
0

你可以寫,可以在其上進行任何操作之前檢查所需要的Webelement存在一個通用的方法。例如,以下方法能夠基於所有支持的標準來檢查Webelement的存在性,例如, XPath的,ID,名稱,標記名,班級等

public static boolean isElementExists(By by){ 
    return wd.findElements(by).size() !=0; 
} 

舉例來說,如果你需要找到基於其XPath中Webelement的存在,您可以在以下方式使用上述方法:

boolean isPresent = isElementExists(By.xpath(<xpath_of_webelement>); 


if(isPresent){ 
     //perform the required operation 
} else { 
     //Avoid operation and perform necessary actions 
} 
相關問題