1)I am doing a tutorial to show how findElements By xpath works. I would like to know why it returns all the texts that following the
Your questions:
Q 1.) I would like to know why it returns all the texts that following the div?
It should not and I think in will not. It returns all div with 'id' attribute value equal 'containter' (and all children of this). But you are printing the results with ele.getText()
Where getText will return all text content of all children of your result.
Get the visible (i.e. not hidden by CSS) innerText of this element, including sub-elements, without any leading or trailing whitespace.
Returns:
The innerText of this element.
Q 2.) how should I modify the code so it just return first or first few nodes that follow the parent note
This is not really clear what you are looking for.
Example:
<p1> <div/> </p1 <p2/>
The following to parent of the div is p2. This would be:
//div[@id='container'][1]/parent::*/following-sibling::*
or shorter
//div[@id='container'][1]/../following-sibling::*
If you are only looking for the first one extent the expression with an "predicate"
(e.g [1]
- for the first one. or [position() < 4]
for the first three)
If your are looking for the first child of the first div:
//div[@id='container'][1]/*[1]
If there is only one div with id an you are looking for the first child:
//div[@id='container']/*[1]
and so on.
The XPath turns into this:
Get me all of the div elements that have an id equal to container.
As for getting the first etc, you have two options.
Turn it into a .findElement()
- this will just return the first one for you anyway.
or
To explicitly do this in XPath, you'd be looking at:
(//div[@id='container'])[1]
for the first one, for the second etc:
(//div[@id='container'])[2]
Then XPath has a special indexer, called last, which would (you guessed it) get you the last element found:
(//div[@id='container'])[last()]
Worth mentioning that XPath indexers will start from 1 not 0 like they do in most programming languages.
As for getting the parent 'node', well, you can use parent:
//div[@id='container']/parent::*
That would get the div's direct parent.
You could then go further and say I want the first *div* with an id of container, and I want his parent:
(//div[@id='container'])[1]/parent::*
Hope that helps!
Instead of
css=#container
use
css=div.container:nth-of-type(1),css=div.container:nth-of-type(2)