deterjan deterjan - 1 year ago 64
HTML Question

Selecting tags by content in Jsoup and getting nth tag after the given tag

I have an HTML document I want to scrape data from. The tag of the data has no unique identifier except that it is the 13th

tag from the
tag containing the given string.

So, for example, the 10th
tag in the document contains the word "dog" ( ie
. Also no other
tag in the document contains identical data.). Given only the word "dog", is it possible for me to extract the content inside the 23rd
tag in the document using Jsoup methods, and if so how?


<td align="center">40</td>
<td align="center">67</td>
<td align="center">58<br>0</td>
<td align="center">32</td>
<td align="center">0</td>
<td align="center">0</td>
<td align="center">58<br>0</td>
<td align="center">99</td>
<td align="center">7</td>
<td align="center">85</td>
<td align="center">58<br>0</td>
<td align="center">13</td>

In a document like this, given only the animal's name, I would like to be able to extract the number in the n'th tag from it, let's say 4. So given "Cat" I would like to find 32. Given "Dog", 99. And for snake 13. Assume there are hundreds of animals in the document.

Answer Source

You can use structural pseudo selectors to target the nth element."td:nth-child(23)");

Since you are looking for the row with Dog, you could select that row first.

Element dogRow ="tr:has(td:contains(dog))").first();

and then select the 23rd child

String cellValue ="td:nth-child(23)").first().ownText();

or combine them

String cellValue = doc
    .select("tr:has(td:contains(dog)) > td:nth-child(23)")


I reread your question and seems like you want to find Dog within a row and then find the nth sibling.

You could use the elementSiblingIndex and getElementsByIndexEquals for this:

    Element dogRow ="tr:has(td:contains(dog))").first();

    int dogCellIndex = dogRow

    int otherCellIndex = dogCellIndex + 10;

    String cellValue = dogRow