ef2011
ef2011

Reputation: 10631

Extract text between two <hr> tags in CSS-less HTML

Using Jsoup, what would be an optimal approach to extract text, of which its pattern is known ([number]%%[number]) but resides in an HTML page that uses neither CSS nor divs, spans, classes or other identifying of any type (yup, old HTML page of which I have no control over)?

The only thing that consistently identifies that text segment (and is guaranteed to remain like that) is that is HTML always looks like this (within a larger body of HTML):

<hr>
2%%17
<hr>

(The number 2 and 17 are examples only. They could be any numbers and, in fact, these are the two variables that I need to reliably extract from that HTML page).

If that text were within an enclosing and uniquely identifying <span> or <div>, I would have no problem extracting it using Jsoup. The problem is that this isn't the case and the only way I can think of right now (which is not elegant at all) is to process the raw HTML through a regex.

Processing the raw HTML through a regex seems inefficient however because I already have it parsed via Jsoup into a DOM.

Suggestions?

Upvotes: 2

Views: 1308

Answers (1)

BalusC
BalusC

Reputation: 1108712

How about this?

Document document = Jsoup.connect(url).get();
Elements hrs = document.select("hr");
Pattern pattern = Pattern.compile("(\\d+%%\\d+)");

for (Element hr : hrs) {
    String textAfterHr = hr.nextSibling().toString();
    Matcher matcher = pattern.matcher(textAfterHr);

    while (matcher.find()) {
        System.out.println(matcher.group(1)); // <-- There, your data.
    }
}

Upvotes: 2

Related Questions