How to interpret an XPath? - selenium

Can someone please tell me if I have interpreted the following XPath correctly:
driver.find_elements_by_xpath ("//span[contains(., 'Cardiovascular')]/parent::*/parent::*/descendant-or-self::node()/a/span"
look for the span tags that have "cardiovascular" as part of their text anywhere in the document
Once it is found, check out its immediate parent and all of its descendants or other parents anywhere in the document and the node itself
Then, go to the immediate a tag
Then, go to the immediate span tag?
More specifically, can someone please tell me what /parent::*/parent means? What /parent::/descendant-or-self::node() means? why do we have node() as a function there

Almost.
Look for the span tags that have "cardiovascular" as part of their text; find their grandparent elements; then within these grandparent elements, find all span elements that have an a element as their parent.

Michael Kay already explained what the XPath selects. Here are the answers to your additional questions:
More specifically, can someone please tell me what /parent::*/parent [sic] means?
parent::* means to select the parent element (* matches elements of any name) of the context node.
parent::*/parent::* means to select the grandparent element of the context node.
What /parent::/descendant-or-self::node() [sic] means?
why do we have node() as a function there
See above for what parent::* means (and note that you forgot the *).
descendant-or-self::node() is the same as .//node(); it selects the context node and all of its descendants. Here, node() is not a function but rather a node test. Had it been element(), it would select only elements; comment(), only comments; etc.

Related

How to find the xpath for an element by text containing three dots

I'm trying to find the xpath for an element that contains three dots instead of text. Once I expand the element by clicking on arrow in DOM model html it returns the text.
The following xpath returns nothing unfortunately:
//button[contains(text(),'Pending')]
What's the right solution?
The text content of that element is not a three dots but Pending (). You see the ... only because there is no room to present the text there until you expand the element. So, generally this //button[contains(text(),'Pending')] should work.
You can also try this XPath expression:
//button[contains(.,'Pending')]
It means "a button element with any attribute containing Pending value"
It is more general and should work.
To understand why //button[contains(text(),'Pending')] did not work see this post or this. There are more explanations about this.

How can I find element by non-unique resousre-id?

I test an application which use non-unique resourse-id for elements.
Is there any way to find such elements by xpath like
//*[#resourse-id='non-unique-id'][2]
I mean the second element with same resourse-id.
I'd recommend avoiding xpath in mobile automation since this is the most time-consuming strategy to find elements.
If you don't have any other anchors for your elements but you confident in its order, you can stick to the following approach: Appium driver can return a list of elements with the same locator, in case of Page Object model you can either do this way:
#AndroidFindBy(uiAutomator = "resourceIdMatches(\".*whatever\")")
private List<MobileElement> elements;
so, once your page is initialized, you can access an element by index:
elements.get(1).click();
or, in case of manual managenemt, you can do this way:
List<MobileElement> elements = driver.findElements(MobileBy.AndroidUIAutomator("resoureceIdMatches(\".*whatever\")"));
elements.get(3).click();
Hope this helps.
As far as my understanding goes, you need to select the second element with the path as mentioned: //*[#resourse-id='non-unique-id']
To do that, you need to first grab all the elements with the same non-unique resource ID and then get() them. So, your code should be:
driver.findElements(By.xpath("//*[#resourse-id='non-unique-id']")).get(1).click();
The index for any list starts at 0. So, the second element can be accessed through the value of 1.
Hope this helps.
Try following approach:
(//*[#resourse-id='non-unique-id'])[2]
HTML with non-unique ids is not a valid HTML document.
So, for the sake of future testability, ask the developers to fix the ids.

What is . (dot) in xpath at place of attribute?

At some places, I saw element like following -
//a[.='Assignment']
Generally we've syntax like - //tagName[attributeKey='attributeValue'] or //tagName[text()='textValue']
But what is intention of . in xpath //a[.='Assignment']?
I'll use XPath 2.0 terminology here: XPath 1.0 has different terminology but the effect of the expression is the same.
"." refers to the context item: that is, the a element that you are testing against the predicate. Its value here is a node. When a node is used as an argument of "=", it is atomized, which means (unless your code is schema-aware, which is unlikely) that the string value of the node is compared with the other operand of "=". The string value of an element is the concatenation of all its descendant text nodes.
It sounds like you don't have ready access to an XPath reference. There are quite a few good books that cover XPath, there are online tutorials (which are highly variable in quality) and the W3C specification itself (especially for XPath 1.0) is surprisingly easy reading.

XPath: difference between dot and text()

My question is about specifics of using dot and text() in XPath. For example, following find_element lines returns same element:
driver.get('http://stackoverflow.com/')
driver.find_element_by_xpath('//a[text()="Ask Question"]')
driver.find_element_by_xpath('//a[.="Ask Question"]')
So what is the difference? What are the benefits and drawbacks of using . and text()?
There is a difference between . and text(), but this difference might not surface because of your input document.
If your input document looked like (the simplest document one can imagine given your XPath expressions)
Example 1
<html>
<a>Ask Question</a>
</html>
Then //a[text()="Ask Question"] and //a[.="Ask Question"] indeed return exactly the same result. But consider a different input document that looks like
Example 2
<html>
<a>Ask Question<other/>
</a>
</html>
where the a element also has a child element other that follows immediately after "Ask Question". Given this second input document, //a[text()="Ask Question"] still returns the a element, while //a[.="Ask Question"] does not return anything!
This is because the meaning of the two predicates (everything between [ and ]) is different. [text()="Ask Question"] actually means: return true if any of the text nodes of an element contains exactly the text "Ask Question". On the other hand, [.="Ask Question"] means: return true if the string value of an element is identical to "Ask Question".
In the XPath model, text inside XML elements can be partitioned into a number of text nodes if other elements interfere with the text, as in Example 2 above. There, the other element is between "Ask Question" and a newline character that also counts as text content.
To make an even clearer example, consider as an input document:
Example 3
<a>Ask Question<other/>more text</a>
Here, the a element actually contains two text nodes, "Ask Question" and "more text", since both are direct children of a. You can test this by running //a/text() on this document, which will return (individual results separated by ----):
Ask Question
-----------------------
more text
So, in such a scenario, text() returns a set of individual nodes, while . in a predicate evaluates to the string concatenation of all text nodes. Again, you can test this claim with the path expression //a[.='Ask Questionmore text'] which will successfully return the a element.
Finally, keep in mind that some XPath functions can only take one single string as an input. As LarsH has pointed out in the comments, if such an XPath function (e.g. contains()) is given a sequence of nodes, it will only process the first node and silently ignore the rest.
There is big difference between dot (".") and text() :-
The dot (".") in XPath is called the "context item expression" because it refers to the context item. This could be match with a node (such as an element, attribute, or text node) or an atomic value (such as a string, number, or boolean). While text() refers to match only element text which is in string form.
The dot (".") notation is the current node in the DOM. This is going to be an object of type Node while Using the XPath function text() to get the text for an element only gets the text up to the first inner element. If the text you are looking for is after the inner element you must use the current node to search for the string and not the XPath text() function.
For an example :-
<a href="something.html">
<img src="filename.gif">
link
</a>
Here if you want to find anchor a element by using text link, you need to use dot ("."). Because if you use //a[contains(.,'link')] it finds the anchor a element but if you use //a[contains(text(),'link')] the text() function does not seem to find it.
Hope it will help you..:)
enter image description here
The XPath text() function locates elements within a text node while dot (.) locate elements inside or outside a text node. In the image description screenshot, the XPath text() function will only locate Success in DOM Example 2. It will not find success in DOM Example 1 because it's located between the tags.
In addition, the text() function will not find success in DOM Example 3 because success does not have a direct relationship to the element . Here's a video demo explaining the difference between text() and dot (.) https://youtu.be/oi2Q7-0ZIBg

What is the meaning of :: in selenium

What is the exact meaning of :: ?
And apart from parent, what else are the different things we can use?
By.xpath("parent::*/parent::*")
The shortest answer I can manage
:: separates an axis name from a node test in an XPath expression.
The longer answer
It does not make much sense to ask about the meaning of ":: in Selenium", because it's not a feature of Selenium. It belongs to XPath, which is a W3C specification in its own right and is used to navigate XML or XHTML documents.
By.xpath(" parent::*/parent::* ")
^ ^ ^
Selenium XPath Selenium
Selenium just happens to embed XPath in their web application framework (which is a good thing!).
So, I've taken the liberty to answer the question: What is the meaning of :: in XPath?
The meaning of :: in XPath
In XPath, :: does not mean anything on its own and only makes sense if there is
a valid XPath axis identifier to the left
a valid node test to the right
For example, parent::* is a valid XPath expression1. Here, parent is an XPath axis name, * is a node test2 - and :: marks the transition from the axis to the node test. Other possible axes are
ancestor following-sibling
ancestor-or-self namespace
attribute parent
child preceding
descendant preceding-sibling
descendant-or-self self
following
Of course those are not just names, they have a very clear-cut semantic dimension: each of them defines a unique way to navigate an XML document (or, rather, a tree-like representation of such a document). Their meaning is straightforward in most cases, for instance, following:: identifies something that "follows" the current context.
These tuples of axis and node test (or triples, also counting predicates) can be "chained together" with the binary / operator to form paths with several steps:
outermost-element/other/third
Navigating a simple document
<root>
<person>James Clark</person>
<person>Steve DeRose</person>
</root>
Naturally, navigation might depend very much on your current whereabouts. There are both absolute and relative path expressions. An example for an absolute path expression is
/child::root/child::person | abbreviated syntax: /root/person
As you can see, there is a / at the beginning of an absolute path expression. It stands for the document node (the outermost node of a tree, which is different from the outermost element node of a a tree). Relative path expressions look like
child::person | abbreviated syntax: person
The relative path expression will only find the person element node if the current context is the root element node. Otherwise, it will fail to locate anything.
Your XPath expression
To sum up and use what we have learned so far:
By.xpath("parent::*/parent::*")
finds the element node that is the grandparent of the current node. The names of both the parent and the grandparent node do not matter (that's what *is for). There's no / at the beginning, so it must be a relative path.
1 In fact, it is a location path, a special kind of XPath expression. Also, I have left out one important concept: predicates. Good things always come in threes, and XPath expressions come with an axis, a node test and with zero or more predicates.
2 A node test must be either a name test (testing the name of a node) or a kind test (testing the kind of node). Find ample information about node tests in the relevant part of the XPath specification.
This is xpath syntax, you can do other things like :
child::* Selects all element children of current node
attribute::* Selects all attributes of current node
child::text() Selects all text node children of current node
child::node() Selects all children of current node
Check a tutorial, especially about axes :
http://www.w3schools.com/xpath/xpath_axes.asp