How do I verify that an element does not exist in Selenium 2

前端 未结 8 1079
误落风尘
误落风尘 2020-12-05 05:29

In Selenium 2 I want to ensure that an element on the page that the driver has loaded does not exist. I\'m including my naive implementation here.

    WebEle         


        
相关标签:
8条回答
  • 2020-12-05 05:50

    I split out page classes so I don't have to define elements more than once. My nunit and mbunit test classes call those page classes. I haven't tried this out yet but this is how I'm thinking about doing it so I can use .exists() like I did with WatiN.

    Extension Class:

    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;
       }
    }
    

    Page Class:

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

    Test Class:

    MyPageClass myPageClass = new MyPageClass(driver);
    if (myPageClass.SaveButton.Exists())
    {
       Console.WriteLine("element doesn't exist");
    }
    
    0 讨论(0)
  • 2020-12-05 05:52

    You can use this:

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

    If it doesn't exist will return true.

    0 讨论(0)
提交回复
热议问题