JavaSheriff
JavaSheriff

Reputation: 7665

Jsoup eq selector returns no value

Trying to fetch data using Jsoup 1.10.3, seems like eq selector is not working correctly.

I tried the nth-child, but it seems like its not getting the second table (table:nth-child(2)).

Is my selector correct?

 html > body > table:nth-child(2) > tbody > tr:nth-child(2) > td:nth-child(2)

in the example below, trying to extract the value 232323

Here is the try it sample

Upvotes: 0

Views: 314

Answers (1)

luksch
luksch

Reputation: 11712

There are several issues that you may be struggling with. First, I don't think that you want to use the :nth-child(an+b) selector. Here is the explanation of that selector from the jsoup docs:

:nth-child(an+b) elements that have an+b-1 siblings before it in the document tree, for any positive integer or zero value of n, and has a parent element. For values of a and b greater than zero, this effectively divides the element's children into groups of a elements (the last group taking the remainder), and selecting the bth element of each group. For example, this allows the selectors to address every other row in a table, and could be used to alternate the color of paragraph text in a cycle of four. The a and b values must be integers (positive, negative, or zero). The index of the first child of an element is 1.

I guess you want to use the :table:nth-of-type(n) selector.

Second, you only select elements with your selector, but you want to get the visible content 232323, which is only one inner node of the element you select. So what is missing is the part where you get to the content. There are several ways of doing this. I again recommend that you read the docs. Especially the cookbook is very helpful for beginners. I guess you could use something like this:

String content = element.text();

Third, with CSS selector you really do to need to go through every hierarchy level of the DOM. Since tables always contain a tbody and tr and td elements, you may do something like this:

String content = document.select("table:nth-of-type(2) tr:nth-of-type(2) td:last-of-type").text();

Note, I do not have a java compiler at hand. Please use my code with care.

Upvotes: 1

Related Questions