簡體   English   中英

Selenium WebDriver:如何確保網頁上的元素可用性?

[英]Selenium WebDriver : How to make sure element availability on Web Page?

在我們對任何 Web 元素執行操作以避免NoSuchElementException異常之前,我已經瀏覽了許多關於如何確保元素可用性的 google 答案。

  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")

上述方法中哪一種是確保元素可用性的最佳方法? 為什么?

除了這些,還有其他方法嗎?

提前致謝。 感謝您的寶貴時間。

public boolean isElementPresentById(String targetId) {

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

        } catch(Exception e) {
            flag = false;
        }
        return flag;
    }
  • 如果該元素可用,您將從方法中獲得 True,否則為 false。
  • 因此,如果您得到 false,則可以避免單擊該元素。
  • 您可以使用上述代碼確認元素的可用性。

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

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

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

所以上面的行將等待元素直到 10 秒,如果元素在不到 10 秒內可用,那么它將停止等待並繼續執行。

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

還有一些其他方法 - @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
}

您可以編寫一個通用方法,該方法可以在對其執行任何操作之前檢查所需的 Webelement 是否存在。 例如,以下方法能夠根據所有支持的標准(例如 xpath、id、name、tagname、class 等)檢查 Webelement 的存在。

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
} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM