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
- Related Articles
- Checking if element exists with Python Selenium.
- How to check if element exists in the visible DOM?
- How to check if event exists on element in jQuery?
- How to check if onClick exists on element in jQuery?
- Check if any alert exists using selenium with python.
- Check if a particular element exists in Java LinkedHashSet
- Java Program to check if a particular element exists in HashSet
- Check if element exists in list of lists in Python
- How to wait until an element no longer exists in Selenium?
- Check if a File exists in C#
- How to check if an item exists in a C# array?
- C# Program to Check if Value exists in Hashtable
- How to Check if a Key Exists in the Hashtable in C#?
- How to use selenium to check if element contains specific class attribute?
- How to check if an item exists in a C# list collection?
Advertisem*nts