XPath For Returning the Column Index XPath For Returning the Column Index selenium selenium

XPath For Returning the Column Index


The following expression returns the position (column index) of the first cell containing the desired text:

count(/html/body/table/tr/td[.='Something'][1]/preceding-sibling::td) + 1


You can get the column index by using selenium.getXpathCount('/html/body/table/tbody/tr/td') and then iterating over the range with selenium.getText('xpath=(/html/body/table/tbody/tr/td)[' + i + ']') until it returns "Something". Remember to count from 1 to n, not 0 to n-1 - XPath counts from 1, not from 0 like many programming languages.


Use:

/html/body/table/tr/td[text() = 'Something']

For XML:

<html>    <body>      <table>       <tr>      <td>Something Else</td>      <td>Something</td>    </tr>    <tr></tr>  </table></body></html>

it selects 2nd td element.