Selenium C# Tutorial: How to Identify Web Elements Using Selenium XPath (Advanced)

Updated: Jan 18

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.


Also:

  • Not like the CSS strategy, XPath can identify the parent element 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.

Finding elements with absolute path

When this technique is used, we will need to deliver the specific location of the element in the DOM hierarchy. As a result, multiple dependencies in the DOM structure can affect the locator's capability to locate the element.


Scenario:

1. log-in to https://demowf.aspnetawesome.com/ .

2. Search for an object in the Autocomplete section

XPath:

string XPath = "//*[@id=\"ContentPlaceHolder1_Meal\"]";


Code


class Program

{

static void Main(string[] args)

{

string XPath = "//*[@id=\"ContentPlaceHolder1_Meal\"]";

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

IWebDriver firefoxDriver = new FirefoxDriver();

TEstPreperation(firefoxDriver, cookieApproval);


IWebElement xpathElement = firefoxDriver.FindElement(By.XPath(XPath));

XPathSearch(xpathElement);

// driver.Quit();

}


private static void TEstPreperation(IWebDriver webDriver ,string cookie)

{

webDriver.Navigate().GoToUrl("https://demowf.aspnetawesome.com/");

Thread.Sleep(3000);

//webDriver.FindElement(By.CssSelector(cookie)).Click();

//Thread.Sleep(3000);

}


private static void XPathSearch(IWebElement XPathElement)

{

if (cssElement.Displayed)

{

XPathElement.SendKeys("Element is available");

}

else

{

Console.WriteLine("Element is NOT found");

}

}



Finding elements with absolute path

Using the element relative path, we can locate the element directly without providing the whole location in the DOM.


Besides, many elements may be matched to the search query when using a relative path. Therefore it will return the first element found in the DOM.


Scenario:

1. log-in to https://demowf.aspnetawesome.com/ .

2. Mark the "Nuts" checkbox using a relative path


Full XPath:

string XPath = "//*[@id=\"maincont\"]/div[1]/div[4]/div[1]/div[2]/div/ul/li[4]/label/div[1]";


Relative Path:

string XPath = "//div/ul/li[4]/label/div[1]";

Code:


class Program

{

static void Main(string[] args)

{

string XPath = "//div/ul/li[4]/label/div[1]";

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

IWebDriver firefoxDriver = new FirefoxDriver();

TEstPreperation(firefoxDriver, cookieApproval);


IWebElement xpathElement = firefoxDriver.FindElement(By.XPath(XPath));

XPathSearch(xpathElement);

// driver.Quit();

}


private static void TEstPreperation(IWebDriver webDriver ,string cookie)

{

webDriver.Navigate().GoToUrl("https://demowf.aspnetawesome.com/");

Thread.Sleep(3000);

//webDriver.FindElement(By.CssSelector(cookie)).Click();

//Thread.Sleep(3000);

}


private static void XPathSearch(IWebElement XPathElement)

{

if (XPathElement.Displayed)

{

XPathElement.SendKeys("Element is available");

}

else

{

Console.WriteLine("Element is NOT found");

}

}


Finding elements based on an index

To overcome the "First element returned" issue that we saw in the previous example, we can search the element via the Index used as another filter.


For example:

Search via full XPath will look like this: //[@id="maincont"]/div[1]/div[4]/div[1]/div[2]/div/ul/li[4]/label/div[1]

Search Via Index will look like this:

"//li[4]/label/div[1]";


Finding elements based on attributes

We can locate elements using their attributes in XPath (Similar to what we saw in the CSS locator).


We will search for the input element (In that case it’s the name field) with the following attributes:

ID attributes:

WebElement = Firefox.FindElement(By.XPath("//input[@id='ContactForm1_contact-form-name']"));


Name attribute:

WebElement = Firefox.FindElement(By.XPath("//input[@name='name']"));

Size attributes:

WebElement = Firefox.FindElement(By.XPath("//input[@size='30']"));



Using Logical operators to filter elements

In some scenarios, you will need to use more than one attribute to locate an element. Using logical operators such as 'Or'/ 'AND' will help you achieve better results in the element filtration process.

Case 1 (Or):

WebElement = Firefox.FindElement(By.XPath("//input[@size='30' or @name='name']"));


Case 2 (And) :

WebElement = Firefox.FindElement(By.XPath("//input[@size='30' and @name='name']"));


Locate element regarding the type of the attribute (* Wildcard)


We can use the * wildcard to search based on an attribute value; the important thing is that the search is made regarding the attribute type.


Example:

If we search for the string "Email," XPath will query all elements and their attributes to validate an attribute value that matched it.


HTML Code:

<input style="width:140px" name="email" type="text">


Code:

WebElement = Firefox.FindElement(By. XPath("//input[@*='email']"));


Using the contains method to handle dynamic elements

Sometimes, you will work with different web applications that dynamically create the element attribute values. Therefore you cannot use a static attribute value that may change every test execution. XPath provides another effective way to locate elements based on a partial part of the attribute value to overcome this issue.


The contains method determines if the attribute value contains the search string we searched for in the locator.


HTML Code

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


ID: "ContactForm1_contact-form-name":


WebElement = Firefox.FindElement(By. XPath("//input[contains(@id,'-name')]"));


Starts-With

Following the previous example, we can do the same thing with the "Starts with" function, but currently, we will examine the beginning of the attribute value.


WebElement = Firefox.FindElement(By.XPath("//input[starts-with(@id,'ContactForm1)]"));


Ends-With

Following the previous example, we can do the same thing with the "Ends With" function, but currently, we will examine the End of the attribute value.


WebElement = Firefox.FindElement(By.XPath("//input[ends-with(@id,'form-name)]"));



Using the Text Method to Identify Web Elements

Sometimes, you will need to locate elements that do not contain any attributes; this issue will make identifying those elements in ordinary strategies challenging.


To overcome this issue, we can use the XPath/CSS text methods that will help us to locate elements using a particular text value.


When using the text function, the locator queries the element for its text content, and if the element contains the relevant text, it will return the element.


Code Examples


HTML:

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


Locating elements using the exact text value

In the following example, we will specify the full text of the XPath locator's element.

WebElement = Firefox.FindElement(By.XPath("//a[.='Quality Assurance']"));

Locating elements using the text function

The text () will return the whole string of the element, and the "Contains" filter will validate if the requested string is matched to the search query.


Code:


WebElement = Firefox.FindElement(By.XPath("//a[contains(text(),'Assurance')]"));

Or

WebElement = Firefox.FindElement(By.XPath("//a[contains(text(),'Quality')]"));



197 views0 comments