Sunday, July 30, 2017

Selenium WebDriver - How to Identify Web Elements Using Selenium XPath Axes

XPath Axes

XPath Axes allowing us to develop a more reboots strategies to locate elements based on nodes relationships, the following table contains the basic Axes that we can use to implement this strategy.
תמונה קשורה

XPath Axes
Description
attribute
Selects all attributes for a specified node
child
Selects all children for a specified node
descendant
Selects all descendants children for a specified node
descendant-or-self
Selects all descendants children for a specified node including the node itself
following
Selects all siblings located after the closing tag of the current node
following-sibling
Selects all siblings that available after the current node
parent
Selects the parent of the current node
preceding
Select all nodes prior to the current node (Filtered: attribute nodes, namespace nodes and ancestors)
preceding -sibling
Selects all siblings located prior to the current node

HTML DOM Nodes

In DOM (Document Object Model) we can say that everything that existing in the doc can be considered as a node:
  • HTML tags are element nodes that you can locate in the DOM tree.
  • HTML comments are considered as comment nodes
  • HTML attributes are considered as attribute nodes.
  • HTML elements are considered as element nodes.
  • The document itself can be considered as a node.
  • Doctype is a DOM node.
  • HTML whitespace nodes (Whitespace symbols in the HTML code (the spaces between the nodes)).

HTML code

<html>
<ul>
<li>="Node 1">First node in list</li>
<li>="Node 2">Second node in list</li>
<li>="Node 3">Third node in list</li>
<li>="Node 4">Fourth node in list</li>
<li>="Node 5">Fifth node in list</li>
<li>="Node 6">Sixth node in list</li>
</ul>
</html>

Code Examples
How to get the preceding values of an element
Firefox.FindElements(By.XPath("//ul/li[contains(text(),'Fourth')]/preceding-sibling::li"));

 

Result:
"Node 1">First node in list
"Node 2">Second node in list
"Node 3">Third node in list

How to get the following values of an element
Firefox.FindElements(By.XPath("//ul/li[contains(text(),'Fourth')]/following-sibling::li"));

Result:
"Node 5">Fifth node in list
"Node 6">Sixth node in list


2 comments:

  1. Selenium is somehow best webdriver. It can help you to identify bugs from web browser.

    ReplyDelete

My Presentations