首页 文章

Selenium WebDriver:如何确保网页上的元素可用性?

提问于
浏览
1

在我们对任何web元素执行操作之前,我已经通过了许多google答案,以确保元素可用性,以避免“NoSuchElementException”异常 .

  • WebDriver driver = new FirefoxDriver();

  • driver.findElement(By.id("userid")) . sendKeys("XUser");

如果元素在页面上不可用,那么第2行将抛出“”NoSuchElementException“ .

我只是想避免抛出这个异常 .

有许多方法可以在WebDriver中进行检查 .

  • isDisplayed()

  • isEnabled()

  • driver.findElements(By.id("userid")) . size()!= 0

  • driver.findElement(By.id("userid")) . size()!= null

  • driver.getPageSource() . contains("userid")

以上方法中最好的一个是确保元素可用性?为什么?

除了这些之外还有其他方法吗?

提前致谢 . 谢谢你宝贵的时间 .

4 回答

  • 1
    public boolean isElementPresentById(String targetId) {
    
            boolean flag = true;
            try {
                webDrv.findElement(By.id(targetId));
    
            } catch(Exception e) {
                flag = false;
            }
            return flag;
        }
    
    • 如果元素可用,您将从方法获得True,否则为false .

    • 因此,如果您得到错误,那么您可以避免单击该元素 .

    • 您可以使用上面的代码确认元素的可用性 .

  • 0

    尝试使用selenium API的显式等待 .

    等待一段时间,直到您在网页上提供所需元素 . 您可以尝试以下示例:

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

    所以上面的行将等待元素直到10秒,如果元素在不到10秒内可用,那么它将停止等待并继续前进执行 .

  • 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,name,tagname,class等 .

    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
    }
    

相关问题