I have xpath
page.search("//table[@class='campaign']//table")
which returns two tables.
I need to choose only first table. This line doesn't work:
page.search("//table[@class='campaign']//table[1]")
How to choose only first table?
Parentheses works! You can also add more path after (..)[ 1], like: '(//div[text() = "'+ name +'"])[1]/following-sibling::*/div/text()' . In case there are many nodes matches name .
For example if both text fields have //input[@id='something'] then you can edit the first field xpath as (//input[@id='something'])[1] and the second field's xpath as (//input[@id='something'])[2] in object repository.
The ancestor axis indicates all the ancestors of the context node beginning with the parent node and traveling through to the root node.
Locating Strategies- (By XPath- Using last())"last() method" selects the last element (of mentioned type) out of all input element present.
This bugged me, too. I still don't exactly know why your solution does not work. However, this should:
page.search("//table[@class='campaign']/descendant::table[1]")
EDIT: As the docs say,
"The location path
//para[1]
does not mean the same as the location path/descendant::para[1]
. The latter selects the first descendant para element; the former selects all descendant para elements that are the first para children of their parents."
Thanks to your question, I finally understood why this works this way :). So, depending on your structure and needs, this should work.
Instead of using an XPath expression to select the first matching element, you can either find all of them and then pare it down:
first_table = page.search("//table[@class='campaign']//table").first
...or better yet, select only the first by using at
:
first_table = page.at("//table[@class='campaign']//table")
Note also that your expression can be found more simply by using the CSS selector syntax:
first_table = page.at("table.campaign table")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With