Parsing elements inside elements in jsoup?

Android Java programming (Eclipse) has recently started, I'm trying to create a simple reader application using jsoup.

I got html for example:

<article id="id" class="artikel"> <h1>Title</h1> <p>paragraph 1</p> <p>paragraph 2</p> <p>paragraph 3</p> </article> <article id="id"> <p>comment1</p> </article> <article id="id"> <p>comment2</p> </article> 

Paragraph sums are variable. Number of comments as well. I want to get all the paragraphs inside the article, none of the comments. This article is always the first tag of the article, so Im uses first () in combination with a template to get it.

The Im method is used here,

 public String GetArticleBody(Document adoc) { //Document totalbody = (Document)adoc.select("article *").first(); //Element totalbody = adoc.select("article *").first(); //Elements paragraphs = adoc.select("article * > p); Elements paragraphs = adoc.select(".article* p"); String body = "test"; for (Element p : paragraphs) { body = StringAttacher(body, p.text()); } System.out.println(body); return body; } 

As you can see, I cheated on the methods from the cookbook and a few that I found in SOF. Of all these methods, all I have ever received is just a word test or nothing at all.

Can someone point me in the right direction to get these paragraphs?

+4
source share
1 answer

You have the wrong selector in your first statement.

. is a "class" selector, so you either use the "article" incorrectly, or you have it . if you do not want.

Try this instead:

 public String GetArticleBody(Document adoc) { //Document totalbody = (Document)adoc.select("article *").first(); //Element totalbody = adoc.select("article *").first(); //Elements paragraphs = adoc.select("article * > p); Elements paragraphs = adoc.select("article").first().select("p"); String body = "test"; for (Element p : paragraphs) { body = StringAttacher(body, p.text()); } System.out.println(body); return body; } 

This will give you the paragraphs in the first article.

Also, it often helps to remember that jsoup selectors are the same as those used in CSS selectors (and a subset of jQuery selectors). Any knowledge that you have from other areas can be used directly using jsoup.

+2
source

Source: https://habr.com/ru/post/1392473/


All Articles