【问题标题】:How do I verify that an element does not exist in Selenium 2如何验证 Selenium 2 中不存在元素
【发布时间】:2021-03-12 13:31:38
【问题描述】:

在 Selenium 2 中,我想确保页面上驱动程序已加载的元素不存在。我在这里包括了我的幼稚实现。

    WebElement deleteLink = null;
    try {
        deleteLink = driver.findElement(By.className("commentEdit"));
    } catch (NoSuchElementException e) {

    }
    assertTrue(deleteLink != null);

是否有一种更优雅的方式可以基本验证断言 NoSuchElementException 被抛出?

【问题讨论】:

    标签: selenium selenium-webdriver


    【解决方案1】:

    如果您正在使用 junit 进行测试,并且这是您正在测试的唯一内容,您可以使用使测试预期异常

    @Test (expected=NoSuchElementException.class)
    public void someTest() {
        driver.findElement(By.className("commentEdit"));
    }
    

    或者您可以使用findElements 方法返回一个元素列表,如果没有找到则返回一个空列表(不抛出NoSuchElementException):

    ...
    List<WebElement> deleteLinks = driver.findElements(By.className("commentEdit"));
    assertTrue(deleteLinks.isEmpty());
    ...
    

    ....
    assertTrue(driver.findElements(By.className("commentEdit")).isEmpty());
    ....
    

    【讨论】:

    • 完美,正是我想要的!非常感谢!
    • 很好的解决方案。但是,它与 ImplicitWait 存在问题,因为对 findElement(s) 的调用会隐式等待元素出现。
    • 您可以通过将等待时间设置为 1 秒或您想要的任何超时来解决此问题。我将其设置为默认值,因此在我的解决方案中,我创建了一个 .net 扩展方法来添加一个 .exists() 方法。 driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(1));
    【解决方案2】:

    你可以用这个:

    Boolean exist = driver.findElements(By.whatever(whatever)).size() == 0;
    

    如果不存在则返回true。

    【讨论】:

    • 是的,我非常喜欢这个解决方案,可惜了,它不直接与 Selenium 分开。
    【解决方案3】:

    我拆分了页面类,因此我不必多次定义元素。我的 nunit 和 mbunit 测试类调用这些页面类。我还没有尝试过,但这就是我正在考虑的方式,所以我可以像使用 WatiN 一样使用 .exists()。

    扩展类:

    public static class ExtensionMethods
    {
       public static IWebElement ElementById(this IWebDriver driver, string id)
       {
          IWebElement e = null;
          try 
          {
             e = driver.FindElement(By.Id(id));
          }
          catch (NoSuchElement){}
          return e;
       }
       public static bool Exists(this IWebElement e) 
       {
          if (e == null)
             return false;  
          return true;
       }
    }
    

    页面类:

    public IWebElement SaveButton { get { try { return driver.ElementById("ctl00_m_m_body_body_cp2_btnSave")); } }
    

    测试类:

    MyPageClass myPageClass = new MyPageClass(driver);
    if (myPageClass.SaveButton.Exists())
    {
       Console.WriteLine("element doesn't exist");
    }
    

    【讨论】:

    • driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(1));
    【解决方案4】:

    您可以使用 driver.findElements("Your elements") 检索元素列表,然后搜索该元素。如果列表不包含您自己想要的行为的元素:)

    【讨论】:

      【解决方案5】:

      如果您使用的是 Javascript API,则可以使用WebElement.findElements()。此方法将返回一个带有已找到元素数组的 Promise。您可以检查数组的长度以确保没有找到任何项目。

      driver.findElements(By.css('.selector')).then(function(elements) {
        expect(elements.length).to.equal(0)
      })
      

      我在 Promise 的回调中使用 Chai 断言库来期望某个值。

      参考:https://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_WebElement.html

      【讨论】:

        【解决方案6】:

        最佳解决方案

          protected boolean isElementPresent(WebElement el){
                try{
                    el.isDisplayed();
                    return true;
                }
                catch(NoSuchElementException e){
                    return false;
                }
            }
        

        【讨论】:

          【解决方案7】:
          public boolean exist(WebElement el){
             try {
                el.isDisplayed();
                return true;
             }catch (NoSuchElementException e){
                return false;
             }
          }
          
          if(exist(By.id("Locator details"))==false)
          

          WebElement el= driver.findElementby(By.locator("locator details")
          public boolean exists(WebElement el)
           try{
            if (el!=null){
             if (el.isDisplayed()){
               return true;
          
              }
             }
           }catch (NoSuchElementException e){
             return false;
           }
          }
          

          【讨论】:

            【解决方案8】:

            使用 webdriver find_element_xxx() 将在我的代码中引发异常并让我们隐式/显式 webdriver 等待的等待时间

            我会去检查 DOM 元素

            webdriver.execute_script("return document.querySelector('your css class')")
            

            附言

            在我们的 QA 主姊妹网站 here 上也发现了类似的讨论


            全面检查可见性+存在性

                # check NOT visible the :aftermeet and :viewintro
                #                   !                .      .                       !       !offsetWidth to check visible in pure js ref. https://stackoverflow.com/a/20281623/248616
                css='yourcss'; e=wd.execute_script(f"return document.querySelector('{css}').offsetWidth > 0") ; assert not e
            
                # check NOT exists :viewintro
                css='yourcss'; e=wd.execute_script(f"return document.querySelector('{css}')") ; assert not e
            

            【讨论】:

              【解决方案9】:

              使用 assertFalse :)

              assertFalse(isElementPresent(By.className("commentEdit")));
              

              【讨论】:

              • 不存在这种方法!
              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2015-08-14
              • 2015-05-29
              • 2012-02-24
              • 1970-01-01
              • 2014-01-05
              • 2012-07-21
              • 2023-02-02
              相关资源
              最近更新 更多