【问题标题】:C# Selenium - Is there any way to check if the Element Exists or not without throwing NoSuchElementExceptionC# Selenium - 有没有办法在不抛出 NoSuchElementException 的情况下检查元素是否存在
【发布时间】:2015-01-21 20:24:09
【问题描述】:

有没有办法使用 selenium C# 来检查页面上是否存在元素而不抛出异常。

【问题讨论】:

    标签: c# selenium nosuchelementexception


    【解决方案1】:

    您的替代方法可能是使用.FindElements。给定一个不匹配任何内容的选择器,它将返回一个空列表,而不是引发异常。

    var elementExists = driver.FindElements(By.ClassName("something")).Any();
    

    Any 是一种 LINQ 方法,仅检查列表是否包含 something(想想.Count == 0)。

    【讨论】:

      【解决方案2】:

      我会使用 explicit 等待的 try catch 块

      public bool CheckElementExist(string state)
      {
          //Write the selector carefully.
          By byCss = By.CssSelector("#view-" + state + "");
          try
          {
           //Explicit wait to check if element exist for 10s   
           new WebDriverWait(Driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementExists(byCss));
              return true;
          }
          catch (NoSuchElementException)
          {
              return false;
          }
      }
      

      【讨论】:

        【解决方案3】:

        http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp

        有一种叫做显式和隐式等待的东西,看看上面的链接。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-02-01
          • 2022-01-20
          • 1970-01-01
          • 2019-06-17
          • 1970-01-01
          • 2020-10-23
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多