Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xpath nearest element to a given element

Tags:

selenium

xpath

I am having trouble returning an element using xpath. I need to get the text from the 2nd TD from a large table.

<tr> 
 <td> 
  <label for="PropertyA">Some text here </label>
 </td>
 <td> TEXT!! </td>
</tr>

I'm able to find the label element, but then I'm having trouble selecting the sibling TD to return the text.

This is how I select the label:

"//label[@for='PropertyA']"

thanks

like image 803
nologo Avatar asked Jan 06 '11 11:01

nologo


People also ask

How can I reach sibling in XPath?

We can use the XPath following sibling axis to find this. So, for this scenario, the XPath expression will be. And we need to identify its sibling “div ” element, as shown below. However, if numerous siblings have the same node, XPath will recognise all of the different elements.

What is difference between ancestor and parent in XPath?

The difference between parent:: and ancestor:: axis is conveyed by their names: A parent is the immediately direct ancestor. So, yes /a/b/c/d/ancestor::*[1] would be the same as /a/b/c/d/parent::* .

Can I get XPath from element in selenium?

Go to the First name tab and right click >> Inspect. On inspecting the web element, it will show an input tag and attributes like class and id. Use the id and these attributes to construct XPath which, in turn, will locate the first name field.


1 Answers

You are looking for the axes following-sibling. It searches in the siblings in the same parent - there it is tr. If the tds aren't in the same tr then they aren't found. If you want to it then you can use axes following.

//td[label[@for='PropertyA']]/following-sibling::td[1]
like image 192
Gaim Avatar answered Sep 19 '22 07:09

Gaim