How to check if Element exists in c# Selenium drivers?


We can check if element exists with Selenium webdriver in C#. This can be determined with the help of the FindElements method. It returns a list of elements which matches the locator passed as a parameter to that method.

If there are no matching elements, an empty list is obtained. In case we have used the method FindElement instead of FindElements, NoSuchElementException will be thrown if there are no matching elements.

For implementation we shall be using the NUnit framework.

Example

using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using System;
using System.Collections.Generic;
namespace NUnitTestProject1{
   public class Tests{
      String u
      = "https://www.tutorialspoint.com/about/about_careers.htm";
      IWebDriver d;
      [SetUp]
      public void Setup(){
         //creating object of FirefoxDriver
         d = new FirefoxDriver();
      }
      [Test]
      public void Test1(){
         //launching URL
         d.Navigate()
         .GoToUrl(u);
         //identify elements and store it in list
         List<IWebElement> e = new List<IWebElement>();
         e.AddRange(d.FindElements
         (By.XPath("//*[text()='Terms of Use']")));
         //checking element count in list
         if (e.Count > 0){
            Console.WriteLine("Element is Present");
         } else {
            Console.WriteLine("Element is not Present");
         }
      }
      [TearDown]
      public void close_Browser(){
         d.Quit();
      }
   }
}

Output

Click on Run All Tests

Click on Open additional output for this result link −

We should get the Test Outcome and Standard Output.

Updated on: 30-Jan-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements