XPath to return a column index

I have the following html:

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

The xpath expression for the first column of the first row:

/html/body/table/tbody/tr/td[2]

I would like to use selenium to get the value "2".

In other words, what is the meaning of the first appearance of the text “Something”. I can get selenium to recognize this element, but not return the value.

Edit: So far, there are excellent answers. But let me make it clear that this is more of a selenium issue, not an xpath issue. I need to figure out how to get selenium in order to return this value.

+5
source share
4 answers

, selenium.getXpathCount('/html/body/table/tbody/tr/td'), selenium.getText('xpath=(/html/body/table/tbody/tr/td)[' + i + ']'), "-". 1 n, 0 n-1. XPath 1, 0, .

+2

( ) , :

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

:

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

XML:

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

td.

0

I think you are trying to dynamically get the index value. If I understand your question correctly. If so, then why not just save the object in the list and get the text of this or that element that you want. This allows for significantly more scalable data parsing and makes your test less fragile.

WebElement thisElement = driver.findElement(By.xPath("//table/tr/"));
List<WebElement> columns = thisElement.findElement(By.tagName("td"));

foreach(WebElement col in columns)
{
  col.Text();
}
0
source

All Articles