Reputation: 21791
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?
Upvotes: 6
Views: 6209
Reputation: 303361
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")
Upvotes: 2
Reputation: 38444
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.
Upvotes: 8