Selenium C# Tutorial: Locating an element using the findElement/s methods (C#, Java and Python)

Updated: Jan 18


Finding elements on the webpage can be challenging due to its complexity. However, web elements are the center of any development and testing process of any application. The interaction between Selenium and web apps is done by a selenium driver, which can locate and handle different tasks related to web elements (e.g., Click, Add Text, Get Attributes, etc.)


Locating elements with Selenium Webdriver is done using the findElement() and findElements() methods driven from the WebElement and WebDriver class.


The findElement() method returns a WebElement object based on specific search criteria (e.g., using the element name, ID, etc.). It produces a "NoSuchElementException" error if it fails to find any element matching the search criteria.


The findElements() method returns a list of WebElements based on search criteria. If the search criteria do not return elements, it returns an empty list. Also,


Find methods take a locator or query object as an instance of By class as an argument. Selenium WebDriver provides By class to support various locator strategies. The following table lists multiple locator strategies supported by Selenium WebDriver:



Find Element By Id

Using the id attribute is preferable to locate elements on a page. Having a unique id attribute provides a very straightforward and reliable way to discover elements on the page as long as the element is set as "static" and not "dynamic."


Syntax:

C#: driver.FindElement(By.Id(<elementID>))

Java: driver.findElement(By.id(<element ID>))

Python: driver.find_element_by_id(<elementID>)


Example:

<input type="text" value="" size="30" name="name" id="ContactForm1_contact-form-name" class="contact-form-name">


WebElement = Firefox.FindElement(By.Id("ContactForm1_contact-form-name"));


Find Element By Name

Although it's sims very logical to find 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.

C#: driver.FindElement(By.Name(<element name>))

Java: driver.findElement(By.name(<element name>))

Python: driver.find_element_by_name(<element name>)


Example:

<input type="text" value="" size="30" name="name" id="ContactForm1_contact-form-name" class="contact-form-name">


WebElement = Firefox.FindElement(By.Name("name"));



Find Element By Class Name

Apart from using the id and name attributes, you can also use the class attribute to locate

elements. The class attribute is provided to apply CSS to an element.


C#: driver.FindElement(By.ClassName(<element class>))

Java: driver.findElement(By.className(<element class>))

Python: driver.find_element_by_class_name(<element class>)


Example

To locate the contact form user name field, we will now use the class attribute:

<input type="text" value="" size="30" name="name" id="ContactForm1_contact-form-name" class="contact-form-name">


WebElement = Firefox.FindElement(By.ClassName("contact-form-name"));


Find Element By Tag Name

Selenium WebDriver provides another strategy to locate web elements using their "Tag Name," in most cases, we will use this strategy when we need to find multiple tags in a web page or when working with tables. Below, keynotes to remember"

  • 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 an error type “NoSuchElementException.”

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


C#: driver.FindElement(By.TagName(<htmltagname>))

Java: driver.findElement(By.tagName(<htmltagname>))

Python: driver.find_element_by_tag_name(<htmltagname >)


Example:

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


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



Find Element By link text/Partial link text

We can search elements using their link attribute; we can use either the full link of the element or only part of it. The first Link with this name will be used when executing the code (In case of duplications). If an element is not found during the code execution, the method returns an error type “NoSuchElementException.”


C#: driver.FindElement(By.LinkText(<linktext >))

Java: driver.findElement(By.linkText(<linktext>))

Python: driver.find_element_by_link_text(<linktext >)


C#: driver.FindElement(By.PartialLinkText(<linktext >))

Java: driver.findElement(By.partialLinkText(<linktext>))

Python: driver.find_element_by_partial_link_text(<linktext >)


Example:

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

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


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

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


Find Element By CSS

Cascading Style Sheets (CSS) is a language used to describe the semantics of the elements of 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.


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...).


We will use the complete path of the element referring to its hierarchy in the DOM (Same as XPath, any changes made in the element's structure hierarchy will cause failure to locate it using the CSS locator).


C#: driver.FindElement(By.CssSelector(<css selector >))

Java: driver.findElement(By.cssSelector(<css selector>))

Python: driver. find_elements_by_css_selector (<css selector>)


Example:


Absolute path

We will use the complete path of the element referring to its hierarchy in the DOM (Same as XPath, any changes made in the element's structure hierarchy will cause failure to locate it using the CSS locator).


Firefox.FindElement(By.CssSelector("html.v2 body.variant………………………div#header.header.section div#Header1.widget.Header div#header-inner div.titlewrapper h1.title")).Text);

}

Relative path

The locator goes directly to the element instead of parsing from the root element. So if the absolute path is defined as "html.v2 body.variant………………………div#header.header.section…div#header-inner div.titlewrapper h1.title"; the relative path will be "h1.title"

Firefox.FindElement(By.CssSelector("h1.title")).Text);



Find Element By Xpath

The XML path language (XPath) is a language that we can use for investigating specific nodes of an XML document based on specific 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.

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

  • Not like the CSS strategy, XPath can identify the parent element using his chilled element.

  • 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 from the current node that match the selection no matter where they are.

C#: driver.FindElement(By. XPath(<xpath query expression>))

Java: driver.findElement(By.xpath (<xpath query expression>))

Python: driver. find_elements_by_xpath (<xpath query expression>)


Example:

absolute path: Firefox.FindElement(By.XPath("/html/body/div[3]/div[2]/div[2]/div[2]/div[1]/div[2]/div[2]/div[1]/div/div/ul/li[3]/a "));


Relative path: Firefox.FindElement(By.XPath("//li[3]/a"));


Elements search using the FindElements function.

As previously explained, we should work with the FindElements method only when we need to work with a list of tags or multiple elements.


Example no'1: Locating table values

The following code will examine each row on table and print it to a local file:

StreamWriter sw = new StreamWriter(@"C:\Debugg.txt", true);

WebElement = Firefox.FindElement(By.XPath("/html/body/table/……"));

IList<IWebElement> ListOfElements = WebElement.FindElements(By.TagName("tr"));

foreach (var item in ListOfElements)

{sw.WriteLine(item.Text);}


Example no'2: Locating multiple elements using a specific attribute


The following code will search for all the <Input> elements with the 'name' attribute (Ignoring the attribute value).


IList<IWebElement> ListOfElements = Firefox.FindElements(By.XPath("input[@name]"));



69 views0 comments