Selenium XPath Tutorial #1 - Introduction to XPath | Basic XPath Syntax

preview_player
Показать описание
XPath is the language used when locating XML (Extensible Markup Language) nodes. XPath is designed to allow the navigation of XML documents, with the purpose of selecting individual elements, attributes, or some other part of an XML document for specific processing.

Xpath can access almost all the elements, even those which doesn’t have class, ID, Name attribute
There are two kinds of Xpaths-

Absolute Xpath- The easiest way of finding the xpath is to use the Browser Inspector tool to locate an element and get the xpath of it.
Xpath : /html/body/div[2]/div/div/footer/section[3]/div/ul/li[3]/a

Above xpath will technically work, but each of those nested relationships will need to be present 100% of the time, or the locator will not function. Above choosed xpath is known as Absolute xpath. There is a good chance that your xpath will vary in every release.

Absolute Xpath starts with a single forward slash(/)

Relative Xpath- A relative xpath is one where the path starts from the node of your choice - it doesn't need to start from the root node. It is always better to choose Relative xpath, as it helps us to reduce the chance of element not found exception.
Relative Xpath starts with a double forward slash(//)

Note : Single slash('/') signifies to look for the element immediately inside its parent and a double slash('//') signifies to look for any child element inside the parent element.

Custom Xpaths:
It is always possible to design your own relative xpath by using different attributes of the Web Element.

1) Contains(): It is a method that is used in an XPath expression. When the value of any attribute changes dynamically, it can locate a web element with the available partial text. Following are the examples of contains () method.

2) Using OR & AND: In the case of the OR expression, we use two conditions. Here either 1st condition OR 2nd condition should be true. It is applied to when one condition is true or both are true. It means that at least one condition should be true to find a web element. Following is the examples of OR expression.

In the case of the AND expression, we use two conditions. Here both conditions should be true to locate a web element. It will fail to locate an element if any of the conditions are false. Following are the examples of AND expression.

3) Start-with function:

This function is used to find a web element whose value of attribute changes on the refresh or on any dynamic operation on the web page. In this expression, we match the starting text of the attribute that is used to locate an element(whose attribute has changed dynamically.)

E.g. On the web page ID of a particular element changes dynamically such as ‘id1’, ‘id2’, ‘id3’, etc. but the text remains the same. Following are the examples of starts-with expression.

Рекомендации по теме