开发者

jsoup tag extraction problem

开发者 https://www.devze.com 2023-01-10 16:52 出处:网络
te开发者_开发知识库st: exampletest1:example1 Elements size = doc.select(\"div:contains(test:)\");

te开发者_开发知识库st: example

test1:example1

 Elements size = doc.select("div:contains(test:)");

how can i extract the value example and example1 from this html tag....using jsoup..


Since this HTML is not semantic enough for the final purpose you have (a <br> cannot have children and : is not HTML), you can't do much with a HTML parser like Jsoup. A HTML parser isn't intented to do the job of specific text extraction/tokenizing.

Best what you can do is to get the HTML content of the <div> using Jsoup and then extract that further using the usual java.lang.String or maybe java.util.Scanner methods.

Here's a kickoff example:

String html = "<div style=\"height:240px;\"><br>test: example<br>test1:example1</div>";
Document document = Jsoup.parse(html);
Element div = document.select("div[style=height:240px;]").first();

String[] parts = div.html().split("<br />"); // Jsoup transforms <br> to <br />.
for (String part : parts) {
    int colon = part.indexOf(':');
    if (colon > -1) {
        System.out.println(part.substring(colon + 1).trim());
    }
}

This results in

example
example1

If I was the HTML author, I would have used a definition list for this. E.g.

<dl id="mydl">
     <dt>test:</dt><dd>example</dd>
     <dt>test1:</dt><dd>example1</dd>
</dl>

This is more semantic and thus more easy parseable:

String html = "<dl id=\"mydl\"><dt>test:</dt><dd>example</dd><dt>test1:</dt><dd>example1</dd></dl>";
Document document = Jsoup.parse(html);
Elements dts = document.select("#mydl dd");
for (Element dt : dts) {
    System.out.println(dt.text());
}
0

精彩评论

暂无评论...
验证码 换一张
取 消