Selenium C# Tutorial: Locators in Selenium

Updated: Jan 18

Selenium WebDriver API provides two functions that we can use for locating Web Elements; each function is used for a different purpose as follows:


The FindElement () function is used when we need to interact with a single element; when executing the function, it will return a single object (Based on the search criteria) or throws up an exception.


The FindElements () function retrieves more than a single element (Collection of elements).


Type of Locators

Finding an element using the ID attribute

The ID attribute is the most common and simplified way to locate web elements.


HTML of element

<input name="ctl00$ContentPlaceHolder1$Meal" id="ContentPlaceHolder1_Meal" class="awe-val awe-autocomplete awe-txt" type="text" autocomplete="off" placeholder="try o" dir="ltr">


Code:


public class Tests

{

public IWebDriver Driver;

public IWebElement WebElement;

[SetUp]

public void Setup()

{

Driver = new FirefoxDriver();

Driver.Navigate().GoToUrl("https://demowf.aspnetawesome.com/");//To open the site

Thread.Sleep(3000);

}


[Test]

public void LocateElementBYId()

{

WebElement = Driver.FindElement(By.Id("ContentPlaceHolder1_Meal"));

WebElement.SendKeys("Test Pass");

}

}



Finding an element using the Name attribute

Although it's sims very logical to find an element by his name, there are a few significant limitations that you need to know:

  • The name attribute may not be unique on a page (the same name can be assigned to multiple elements).

  • If you use this attribute and it's assigned to multiple elements, the first element on the page with this name will be returned by the API.

HTML of element

<input name="ctl00$ContentPlaceHolder1$Meal" id="ContentPlaceHolder1_Meal" class="awe-val awe-autocomplete awe-txt" type="text" autocomplete="off" placeholder="try o" dir="ltr">


Code:


public class Tests

{

public IWebDriver Driver;

public IWebElement WebElement;

[SetUp]

public void Setup()

{

Driver = new FirefoxDriver();

Driver.Navigate().GoToUrl("https://demowf.aspnetawesome.com/");//To open the site

Thread.Sleep(3000);

}


[Test]

public void LocateElementBYname()

{

WebElement = Driver.FindElement(By.Name("ctl00$ContentPlaceHolder1$Meal"));

WebElement.SendKeys("Test Pass");

}

}


Result:


Finding an element using the LinkText attribute

We can search for elements using their link attribute; we can use a whole link part.


HTML of element

<a href="http://www.machtested.com/p/blog-page_11.html">Quality Assurance</a>


Code

To locate the contact form user name field, we will now use the "link Text" attribute:


[TestMethod]

public void FindElementByLinkText()

{

IWebElement WebElement;

IWebDriver Firefox = new FirefoxDriver();

Firefox.Navigate().GoToUrl("http://www.machtested.com/");

WebElement = Firefox.FindElement(By.LinkText("Quality Assurance"));

}


[TestMethod]

public void FindElementByPartialLinkText()

{

IWebElement WebElement;

IWebDriver Firefox = new FirefoxDriver();

Firefox.Navigate().GoToUrl("http://www.machtested.com/");

WebElement = Firefox.FindElement(By.PartialLinkText("Quality"));

}


Finding an element using the ClassName attribute

we can also search for an element using its class name.


HTML of element

<input class="gsc-search-button" title="search" type="submit" value="Search">


public class Tests

{

public IWebDriver Driver;

public IWebElement WebElement;

[SetUp]

public void Setup()

{

Driver = new FirefoxDriver();

Driver.Navigate().GoToUrl("http://www.machtested.com/");//To open the site

Thread.Sleep(3000);

}


[Test]

public void LocateElementClassName()

{

WebElement = Driver.FindElement(By.ClassName("gsc-search-button"));

WebElement.Click();

}

}




Finding an element using the TagName attribute

Another strategy is to locate web elements using their "Tag Name," in most cases, we will use it when we need to find multiple tags on a web page or when working with tables.

Besides,

  • There is no reason to work with this locator when you need a single element.

  • If possible, make sure that the selected TAG is unique.

  • When the element is not found during the code execution, the method returns the error type “NoSuchElementException.”

  • The first TAG with this name will be used when executing the code (In duplications).

To locate the main title element in my old blog, we will now use the "Tag Name" attribute:

HTML of element


<div class="titlewrapper"><h1 class="title"> David Tzemach's Blog </h1></div>

Code Example

[TestMethod]

public void FindElementByTagName()

{

IWebElement WebElement;

IWebDriver Firefox = new FirefoxDriver();

Firefox.Navigate().GoToUrl("http://www.machtested.com/");

WebElement = Firefox.FindElement(By.TagName("h1"));

}

Finding an element using CSS

Cascading Style Sheets (CSS) is a language used to describe the semantics of the elements related to a document written in an HTML or XML syntax (The element's style and how it is represented on the screen).


When using CSS, we can review the pattern–matching (Known as “Selectors”) rules defined for different DOM elements.

For more information about CSS:

https://en.wikipedia.org/wiki/Cascading_Style_Sheets


Selenium WebDriver can use the structure and identifiers of the CSS syntax to locate elements in DOM; this strategy is superior to XPath (More reliable and will work faster...).


In the following example, I will connect to my site and press the "Blog" button:

How to get the CSS structure? Easy.. check the example below:



Code:


class Program

{

static void Main(string[] args)

{

string cssPath = "#comp-khbyvzuo1label";

IWebDriver driver = new FirefoxDriver();

driver.Navigate().GoToUrl("http://www.agilequalitymadeeasy.com/");

Thread.Sleep(3000);

IWebElement element = driver.FindElement(By.CssSelector(cssPath));

CSSExample(element);

driver.Quit();

}

private static void CSSExample(IWebElement webElement1)

{

if (webElement1.Displayed)

{

webElement1.Click();

Console.WriteLine("Element is available");

}

else

{

Console.WriteLine("Element is not available");

}

}



Finding an element using XPath

The XML path language (XPath) is a language that we can use for investigating specific nodes of an XML document based on detailed search criteria.


Selenium WebDriver supports the XML path language as a strategy to locate elements using flexible XPath queries; this fact is significant because all the major browsers (Firefox, IE, and chrome) support it.


Besides:

  • Like the CSS strategy, XPath can identify parent elements using his chilled element.

  • XPath is the least preferable strategy to locate elements due to reduced performance compared to other strategies.

  • A single / slash at the beginning of the XPath instructs the XPath locator to search for elements starting from the root node.

  • A double // slash at the beginning of the XPath instructs the XPath locator to search the element anywhere.

Scenario:

In the following code example, I will log in to my blog, approve the cookie banner, and navigate to the "My Experience" section.



Code

static void Main(string[] args)

{

string XPath = "//*[@id=\"comp-khbyvzuo2label\"]";

string CookieApproval = "html body.device-windows div._2svEM._2f7c5._4Ck7e div.HzPhN div._1STS6 button.undefined.MWTAz._6WUOF";

IWebDriver driver = new FirefoxDriver();

driver.Navigate().GoToUrl("http://www.agilequalitymadeeasy.com/");

Thread.Sleep(3000);


driver.FindElement(By.CssSelector(CookieApproval)).Click();

Thread.Sleep(3000);

IWebElement element = driver.FindElement(By.XPath(XPath));

XPathExample(element);

// driver.Quit();

}

private static void XPathExample(IWebElement webElement1)

{

if (webElement1.Displayed)

{

webElement1.Click();

Console.WriteLine("Element is available");

}

else

{

Console.WriteLine("Element is not available");

}

}







200 views0 comments