JSOUP scrape html text from p and span

為{幸葍}努か 提交于 2020-01-04 06:32:25

问题


I'm having a hard time getting the correct output. Please see below sample text from HTML:

 <p><span class="v">1</span> Een psalm van David. De HEERE is mijn Herder, mij zal niets ontbreken.</p>

 <p><span class="v">2</span> Hij doet mij nederliggen in grazige weiden; Hij voert mij zachtjes aan zeer stille wateren.</p>

 <p><span class="v">3</span> Hij verkwikt mijn ziel; Hij leidt mij in het spoor der gerechtigheid, om Zijns Naams wil.</p>

I want to get the value of paragraph

that is Een psalm van David. De HEERE is mijn Herder, mij zal niets ontbreken. based on user's selected verse

So far this is what I've done:

HttpGet get = new HttpGet(url);
HttpResponse resp = client.execute(get);

String content = EntityUtils.toString(resp.getEntity());
Document doc = Jsoup.parse(content);

StringBuilder sb = new StringBuilder();

Elements passage = doc.select("p > span.v");

sb.append(passage.text() + "\n");

Elements links = doc.select(className);
for (Element link : links) {
    sb.append(link.text() + " ");
}
Log.e("ELEMENTS", "" + sb.toString());
response = sb.toString();

But I'm only getting the verse numbers. How do I get the correct output? I would gladly appreciate any help. Thanks.


回答1:


Assuming that you want to get the paragraph of verse 1, you can do it using:

  1. :has(selector) to get only elements that contain elements matching the selector
  2. Then use as selector span.v:containsOwn(1) to indicate that you want a span of class v whose text contains 1.
  3. And finally use ownText() to get the text of the element itself not the text of its children too, otherwise if you want both use text().

So the code could be:

String className = "v";
int verse = 1;
Element p = doc.select(String.format("p:has(span.%s:containsOwn(%d))", className, verse))
    .first();
System.out.println(p.ownText());

Output:

Een psalm van David. De HEERE is mijn Herder, mij zal niets ontbreken.

If you want to get all paragraphs' content, the code could be:

StringBuilder sb = new StringBuilder();
Elements paragraphs = doc.select("p:has(span.v)");
for (Element p : paragraphs) {
    sb.append(p.ownText() + "\n");
}
System.out.println(sb);

Output:

Een psalm van David. De HEERE is mijn Herder, mij zal niets ontbreken.
Hij doet mij nederliggen in grazige weiden; Hij voert mij zachtjes aan zeer stille wateren.
Hij verkwikt mijn ziel; Hij leidt mij in het spoor der gerechtigheid, om Zijns Naams wil.


来源:https://stackoverflow.com/questions/40522752/jsoup-scrape-html-text-from-p-and-span

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!