XPath:: Get following Sibling

HtmlXpathSiblingsScraper

Html Problem Overview


I have following HTML Structure: I am trying to build a robust method to extract second color digest element since there will be many of these tag within the DOM.

<table>
  <tbody>
    <tr bgcolor="#AAAAAA">
    <tr>
    <tr>
    <tr>
    <tr>
      <td>Color Digest </td>
      <td>AgArAQICGQMVBBwTIRQHIwg0GUMURAZTBWQJcwV0AoEDAQ </td>
    </tr>
    <tr>
      <td>Color Digest </td>
      <td>2,43,2,25,21,28,0,0,0,0,0,0,0,0,0,0,0,0,0,0,33,7,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,25,0,0,0,0,0,0,0,0,0,0,0,0,0,0,20,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,9,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, </td>
    </tr>
  </tbody>
</table>

I am trying to extract the Second "Color Digest" td element that has the decoded value.

I wrote the following xpath but instead of getting the second i am not getting the second td element.

//td[text() = ' Color Digest ']/following-sibling::td[2]

And when I change it to td[2] to td[1] I get both the elements.

Html Solutions


Solution 1 - Html

You should be looking for the second tr that has the td that equals ' Color Digest ', then you need to look at either the following sibling of the first td in the tr, or the second td.

Try the following:

//tr[td='Color Digest'][2]/td/following-sibling::td[1]

or

//tr[td='Color Digest'][2]/td[2]

http://www.xpathtester.com/saved/76bb0bca-1896-43b7-8312-54f924a98a89

Solution 2 - Html

You can go for identifying a list of elements with xPath:

//td[text() = ' Color Digest ']/following-sibling::td[1]

This will give you a list of two elements, than you can use the 2nd element as your intended one. For example:

List<WebElement> elements = driver.findElements(By.xpath("//td[text() = ' Color Digest ']/following-sibling::td[1]"))

Now, you can use the 2nd element as your intended element, which is elements.get(1)

Solution 3 - Html

/html/body/table/tbody/tr[9]/td[1]

In Chrome (possible Safari too) you can inspect an element, then right click on the tag you want to get the xpath for, then you can copy the xpath to select that element.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionadd-semi-colonsView Question on Stackoverflow
Solution 1 - Htmljames31rockView Answer on Stackoverflow
Solution 2 - HtmlDhaval JethavaView Answer on Stackoverflow
Solution 3 - HtmlFarFigNewtonView Answer on Stackoverflow