andgursky andgursky - 5 months ago 58
Ruby Question

how to get data element by title index with capybara "find"?

I have html page:



<html>
<body>
<th>a</th>
<th>b</th>
<th>c</th>
<th>d</th>
<th>e</th>
<th>f</th>
<th>g</th>
<th>h</th>
<th>i</th>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
</body>
</html>





I need to get data (td tag) by choosing title (th tag).
I'm trying:

page.find(:xpath, "//body/td[count(//body/th[contains(.,'a')]/preceding-sibling::th)-1]")


and I'm expecting to get "1" as returning value, but it returns "8".
It seems to me, that "count" doesn't work right. So, what am I doing wrong?

Answer

The logic should've counted preceding-sibling th plus 1, to find the correct position index of the th :

//body/td[count(//body/th[contains(.,'a')]/preceding-sibling::th)+1]

xpathtester demo

output :

<td>1</td>
Comments