Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xpath choose first table

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?

like image 613
megas Avatar asked Apr 05 '12 19:04

megas


People also ask

How do you select the first element in XPath?

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 .

How do you select the second element with the same XPath?

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.

What is ancestor in XPath?

The ancestor axis indicates all the ancestors of the context node beginning with the parent node and traveling through to the root node.

How do I get the last child in XPath?

Locating Strategies- (By XPath- Using last())"last() method" selects the last element (of mentioned type) out of all input element present.


2 Answers

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.

like image 170
Petr Janeček Avatar answered Oct 09 '22 03:10

Petr Janeček


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")
like image 45
Phrogz Avatar answered Oct 09 '22 03:10

Phrogz