gpt4 book ai didi

java - Jsoup:在无 CSS 的 HTML 中提取两个 block 之间的所有 HTML

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:28:45 25 4
gpt4 key购买 nike

使用 Jsoup 提取符合此模式的两个 block 之间的所有 HTML(字符串、文档或元素)的最佳方法是什么:

<strong>
{any HTML could appear here, except for a <strong> pair}
</strong>

...
{This is the HTML I need to extract.
any HTML could appear here, except for a <strong> pair}
...

<strong>
{any HTML could appear here, except for a <strong> pair}
</strong>

如果我将它应用到整个 body.html() 上,使用正则表达式这可能很简单:

(<strong>.+</strong>)(.+)(<strong>.+</strong>)
^
+----- There I have my HTML content

但正如我从 similar challenge 中了解到的那样,如果我使用已经由 Jsoup 解析的 DOM,则可以提高性能(即使代码稍长)——除了这次 Element.nextSibling()Element.nextElementSibling( ) 可以帮上忙。

我搜索了类似 jQuery 的 nextUntil 的东西例如,在 Jsoup 中,但找不到类似的东西。

是否有可能想出比上述基于正则表达式的方法更好的方法?

最佳答案

我不知道它是否更快,但也许像这样的东西会起作用:

Elements strongs = doc.select("strong");
Element f = strongs.first();
Element l = strongs.last();
Elements siblings = f.siblingElements();
List<Element> result = siblings.subList(siblings.firstIndexOf(f) + 1,siblings.lastIndexOf(l));

关于java - Jsoup:在无 CSS 的 HTML 中提取两个 block 之间的所有 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7302676/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com