How do I select this element in JSOUP?

HackToHell picture HackToHell · May 22, 2012 · Viewed 29.7k times · Source

This is the HTML structure:

enter image description here

Element link = doc.select("div.subtabs p").first();

That does not seem to work. How do I select that p?

Answer

jmort253 picture jmort253 · May 22, 2012

The DIV with the class="subtabs" is not in fact the parent of the p element but instead is the sibling of p. To retrieve the p, you'll need to first get a reference to the parent DIV that has the id="content":

Element link = doc.select("div#content > p").first();

Additionally, you'll need the > symbol to indicate that you're selecting a child of div#content.

parent > child: child elements that descend directly from parent, e.g. div.content > p finds p elements; and body > * finds the direct children of the body tag

If you get stuck with a JSOUP CSS selector in the future, check out the JSOUP Selector Syntax cookbook, which has some nice examples and explanations.