开发者

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

开发者 https://www.devze.com 2023-04-01 22:24 出处:网络
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 i

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?


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.
    }
}
0

精彩评论

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