0

I have the following HTML structure

<tr> 
  <td><input name="Choice" type="radio" value="someValue"></td>
  <td><a href="">text</a></td>
</tr>

I would like to write a Xpath that finds the link by the value of its text then search the input element and perform an action like click on the input radio button.

I have tried a number of Xpaths like this one

//a[contains(text(), 'text')]/ancestor::/td/input

but they all fail. The first part of the xpath is right but the second path with the ancestor is where it gets into trouble.

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352

4 Answers4

1
//tr[.//[contains(text(), 'text')]]//input

You can search for the common wrapper first, that has text inside. And then just search required element in that wrapper.

It doesn't care about order of the elements, which can be good or not, depending on your task. It also doesn't care about elements being on the same level, but both elements should be inside tr tag.

You can be more precise by adding inner path, or attributes select.

//tr[td[contains(text(), 'text')]]/td/input

This pattern is rarely used for some reason, but I would recommend it for it's readability, simplicity, and straight-forward approach.

Vitaliy Moskalyuk
  • 2,463
  • 13
  • 15
0
//a[contains(text(), 'text')]/../..//input

or

//a[contains(text(), 'text')]/ancestor::tr/td/input

just use '..' goto the immediate parent and then find the input child tag of that

you have to mention which ancestor tag to be select

PDHide
  • 18,113
  • 2
  • 31
  • 46
0

You were close enough. To locate the <input> element with respect to the <a> tag with text as text you can use either of the following Locator Strategies:

  • Using the <td> and it's child attributes:

    //td[.//a[text()='text']]//preceding::td[1]/input
    
  • Using the textContext of <a>:

    //a[text()='text']//preceding::td[1]/input
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
-1

If you want to select input node by link text try

//td[a="text"]/preceding-sibling::td/input
JaSON
  • 4,843
  • 2
  • 8
  • 15