【问题标题】:Best way to check that element is not present using Selenium WebDriver with java使用 Selenium WebDriver 和 java 检查该元素不存在的最佳方法
【发布时间】:2012-08-29 12:04:37
【问题描述】:

我正在尝试下面的代码,但它似乎不起作用...有人可以告诉我最好的方法吗?

public void verifyThatCommentDeleted(final String text) throws Exception {
    new WebDriverWait(driver, 5).until(new ExpectedCondition<Boolean>() {
            @Override
            public Boolean apply(WebDriver input) {
                try {
                    input.findElement(By.xpath(String.format(
                            Locators.CHECK_TEXT_IN_FIRST_STATUS_BOX, text)));
                    return false;
                } catch (NoSuchElementException e) {
                    return true;
                }
            }
        });
    }

【问题讨论】:

  • 作为替代方案,您可以使用“WebdriverBackedSelenium”并使用 selenium.isElementPresent("Locator");
  • 首先 input.findElements(By.xpath("//xpath")).size() > 0 是比在 try..catch 中包装 findBy 更好的方法来验证元素的存在。第二件事是:“它不起作用”是什么意思?会挂吗?抛出异常?返回不正确的结果?

标签: java selenium-webdriver assertion verify


【解决方案1】:

不执行 findElement,而是执行 findElements 并检查返回元素的长度是否为 0。这就是我使用 WebdriverJS 的方式,我希望在 Java 中同样可以工作

【讨论】:

  • 其实这也是官方文档推荐的:"findElement 不应该用于查找不存在的元素,使用 findElements(By) 并断言零长度响应。" Javadoc for WebElement#findElement
  • 是的,这是官方的做法,但不幸的是docs 也说:“此方法受执行时有效的'隐式等待'时间的影响。” 所以你最终可能会做类似driver.manage.timeouts.implicitlyWait(10, TimeUnit.MILLISECONDS) 的事情(可能使用finally 再次重置超时)。
【解决方案2】:

我通常有几个方法(成对)来验证元素是否存在:

public boolean isElementPresent(By locatorKey) {
    try {
        driver.findElement(locatorKey);
        return true;
    } catch (org.openqa.selenium.NoSuchElementException e) {
        return false;
    }
}

public boolean isElementVisible(String cssLocator){
    return driver.findElement(By.cssSelector(cssLocator)).isDisplayed();
}

请注意,有时 selenium 可以在 DOM 中找到元素,但它们可能是不可见的,因此 selenium 将无法与它们交互。所以在这种情况下,检查可见性的方法会有所帮助。

如果您想等待元素直到它出现,我发现的最佳解决方案是使用流利的等待:

public WebElement fluentWait(final By locator){
    Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
            .withTimeout(30, TimeUnit.SECONDS)
            .pollingEvery(5, TimeUnit.SECONDS)
            .ignoring(NoSuchElementException.class);

    WebElement foo = wait.until(new Function<WebDriver, WebElement>() {
        public WebElement apply(WebDriver driver) {
            return driver.findElement(locator);
        }
    });

    return foo;
};

希望这会有所帮助)

【讨论】:

  • 您的代码可能存在竞争条件:该元素可能在调用 findElementisDisplayed 之间被删除 - 这意味着您将随机获得 StaleElementReferenceExceptions。
  • @sleske,每种情况都应特别考虑,即我们需要决定元素:1)它是否出现在页面上/不存在 2)vsibile/不可见。所以combo fluentWait(#selector).isDisplayed() 会处理它,因为:1)如果元素不存在>>exception noSuchElement 2)如果元素存在>>然后我们得到它的可见性。
  • isElementVisible 的潜在建议: public boolean isElementVisible(By locatorKey) { return driver.findElement(locatorKey).isDisplayed(); } 感谢您的 cmets。
【解决方案3】:

使用 findElements 代替 findElement

如果没有找到匹配的元素,

findElements 将返回一个空列表,而不是异常。另外,我们可以确定元素是否存在。

例如:列表元素 = driver.findElements(By.yourlocatorsstrategy);

if(elements.size()>0){
    do this..
 } else {
    do that..
 }

【讨论】:

  • 欢迎来到 SO!虽然这是一个正确(且格式正确)的答案,但它已经列在答案部分并且已经有将近 5 年的历史了,因此它并没有真正带来任何新的东西。查看未回答的问题以开始提供帮助!
【解决方案4】:

无法对流星测试手册发表评论,因为我没有代表,但我想提供一个我花了很长时间才弄清楚的例子:

Assert.assertEquals(0, wd.findElements(By.locator("locator")).size());

此断言验证 DOM 中没有匹配的元素并返回零值,因此当元素不存在时断言通过。如果它存在,它也会失败。

【讨论】:

  • 谢谢你的例子。
【解决方案5】:
int i=1;

while (true) {
  WebElementdisplay=driver.findElement(By.id("__bar"+i+"-btnGo"));
  System.out.println(display);

  if (display.isDisplayed()==true)
  { 
    System.out.println("inside if statement"+i);
    driver.findElement(By.id("__bar"+i+"-btnGo")).click();
    break;
  }
  else
  {
    System.out.println("inside else statement"+ i);
    i=i+1;
  }
}

【讨论】:

  • 如何通过增加 i 值来检查 id 会抛出异常
  • 它确实会引发异常。我正要提这个。正确的方法是获取“findElements”的长度并查看它是否等于“0”。如果为 0,则该元素不存在。如果它大于“1”,则该元素仍然存在。唯一会破坏这种逻辑的是页面上是否有多个元素具有相同的 ID 或 NAME。在这种情况下,您可以与开发团队交谈,或者通过 XPath 等其他方式获得它。
  • 显然我的编辑被拒绝了,所以这是我在编辑中的评论。 ““WebElementdisplay”会导致错误,需要一个空格“WebElement display”。“i = i + 1”,应该简单地完成为“i++”。(display.isDisplayed == true)应该只是(display.isDisplayed)。”
【解决方案6】:
WebElement element = driver.findElement(locator);
Assert.assertNull(element);

如果元素不存在,上述断言将通过。

【讨论】:

    【解决方案7】:
    public boolean isDisplayed(WebElement element) {
            try {
                return element.isDisplayed();
            } catch (NoSuchElementException e) {
                return false;
            }
        }
    

    如果您想检查该元素是否显示在页面上,您的检查应该是:

    if(isDisplayed(yourElement){
    ...
    }
    else{
    ...
    }
    

    【讨论】:

      【解决方案8】:

      在 Python 中我使用断言:

      assert len(driver.find_elements_by_css_selector("your_css_selector")) == 0
      

      【讨论】:

        【解决方案9】:

        我的答案要简单得多,而且对我有用

        while(true) {
        if (driver.getPageSource().contains("Enter the text of the element you wanted to check")==false) 
        {//Put your code here 
            break;
        }   
        else if (isElementPresent(element you are trying to find)==true)
        {
                        //put your code here 
                        break;
        }
        

        }

        【讨论】:

          【解决方案10】:
              WebElement element = driver.findElement(locator);
          
              Assert.assertFalse(element.isDisplayed());
          

          如果元素不存在,断言将通过,否则将失败。

          【讨论】:

          • 它将在第一行抛出异常,因为没有这样的元素
          猜你喜欢
          • 2013-09-08
          • 2015-06-07
          • 2013-10-30
          • 1970-01-01
          • 2015-05-29
          • 1970-01-01
          • 2015-09-09
          • 2016-12-25
          • 1970-01-01
          相关资源
          最近更新 更多