提取两个< hr>之间的文本无需CSS的HTML中的标签 [英] Extract text between two <hr> tags in CSS-less HTML

查看:90
本文介绍了提取两个< hr>之间的文本无需CSS的HTML中的标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Jsoup,这是提取文本的最佳方法,其模式是已知的([number]%%[number]),但是位于HTML页面中,该页面既不使用CSS也不使用div,span,class或其他任何类型的标识(是的,我无法控制的旧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)?

唯一能持续标识该文本段(并保证保持不变)的是HTML 始终看起来像这样(在较大的HTML正文中):

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>

(数字2和17仅是示例.它们可以是任何数字,实际上,这是我需要可靠地从该HTML页面提取的两个变量).

(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).

如果该文本在一个封闭的且唯一标识<span><div>的文本内,那么使用Jsoup提取文本将没有问题.问题在于情况并非如此,我现在唯一可以想到的方法(根本不是很优雅)是通过以下方式处理原始 HTML:正则表达式.

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.

通过正则表达式处理原始HTML似乎效率低下,因为我已经通过Jsoup将其解析为DOM.

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

建议?

推荐答案

如何?

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

这篇关于提取两个&lt; hr&gt;之间的文本无需CSS的HTML中的标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆