Reputation: 16290
I have an HTML document in which there is a table that contains rows that might or might not have a class, for example:
<tr class="">
<th>Name</th>
<td class="row-text">Myname</td>
</tr>
In the above example, the row doesn't have a class. However I need to get the column value (ie. MyName
). The only unique value in such rows the is the header tag.
Is there a way to get the correct row by header value using XPath?
Upvotes: 2
Views: 321
Reputation: 1282
@alecxe answer is right. I would add other similar alternatives:
This one looks for all the tr
with a th
that contain 'Name'
as a substring (if there are more than one element with the text 'Name' as part of their content they will be selected too); and chooses the td
inside the tr
//tr[contains(th, 'Name')]/td
This other is similar, but only gives you the elements with the exact match, and also takes care of normalizing the whitespaces, which is useful as sometimes exact matches are not found because there might be whitespaces or newlines before the text that prevent the exact match. It finds the th
moves to the parent (..
) and finally to the td
//th[normalize-space(text()) = 'Name']/../td
Remember that you can use the $x("some/xpath")
function in the Chrome and Firefox consoles to check for xpaths; similar to the $("some css")
for CSS selectors.
Upvotes: 1
Reputation: 473833
Yes, you can do it with the following-sibling
axis:
//th[. = 'Name']/following-sibling::td
Or, through the tr
parent element:
//tr[th = 'Name']/td
Upvotes: 3