gpt4 book ai didi

java - 如何使用 CSS 选择器获取 "first element X after the element Y"?

转载 作者:行者123 更新时间:2023-11-30 08:04:43 25 4
gpt4 key购买 nike

在 Java 应用程序中,想象一下我在一个巨大的 HTML 代码中的某处有这个:

<h2>
<b>
This
</b>
</h2>

<h1>
</h1>

假设我想获取元素 b 之后的第一个元素 h1。我已经通过 JSoup 库尝试了一些 CSS 选择器,但没有发现任何有用的东西。这里最大的问题是:他们不是 sibling 。我不知道 b 元素是否是不同父元素的子元素。

有办法吗?

最佳答案

您不能纯粹使用 CSS 选择器来完成此操作,您必须使用 JSoup 在代码中执行一些逻辑。

该算法适用于浏览器和 JSoup 文档。基本上,从 b 元素开始,您可以通过以下方式找到 h1:

  1. 当前设置为b
  2. 当前不为null时:
    1. sibling 设置为 current下一个元素同级(在 JSoup 中,这将是 nextElementSibling method ;在任何现代浏览器中,它是 nextElementSibling 属性
    2. sibling不为null时:
      1. 如果 siblingh1,则完成
      2. 否则,将 sibling 设置为 sibling 的下一个同级元素,并继续此同级循环(“while sibling 不是 null")
    3. (sibling is null) 将 current 设置为 current 的父节点。在 JSoup 中,这将是 parent method 。在浏览器中,它将是 parentNode 属性
    4. 如果 currentnull,则继续此父循环(“while current is not null” )。
    5. 没有以下 h1

关于java - 如何使用 CSS 选择器获取 "first element X after the element Y"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31299806/

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