0

I've come across cases when there are lots of links on the page and the following xpath works for choosing the first one:

//tag[@...]/div/a[1]

There are other cases when the above xpath doesn't work and then I need to use it the following way:

(//tag[@...]/div/a)[1]

As I write lengthier xpaths to code in business logic for which elements to select, this difference starts getting all the more complicated where the same xpath has multiple combinations of both of these.

What is the difference exactly between writing xpaths in these two ways? I've seen that for any particular occasion one of them works and the other doesn't.

Mugen
  • 1,417
  • 5
  • 22
  • 40

1 Answers1

1

Consider this sample HTML:

<table>
  <tbody>
    <tr>
      <td>1.1</td>
      <td>1.2</td>
      <td>1.3</td>
    </tr>
    <tr>
      <td>2.1</td>
      <td>2.2</td>
      <td>2.3</td>
    </tr>
    <tr>
      <td>3.1</td>
      <td>3.2</td>
      <td>3.3</td>
    </tr>
  </tbody>
</table>

Here you can use //table/tbody/tr/td[index] to go through <td> elements of only first row <tr>. //table/tbody/tr will return the first match, which is your first row and then indexing is done only on the <td> elements in first row. So valid indexes are 1,2,3.

But you can use (//table/tbody/tr/td)[index] if you want to go through all <td> values in the table. Here the indexing applies on the whole xpath which is same for all the <td> elements. So valid indexes are 1,2,3,..9.

Kamal
  • 2,384
  • 1
  • 13
  • 25