java - Jsoup 选择深度元素(来自父级的 DOM 级别)

标签 java jsoup

这是一些原始的 HTML(取自一个大文件):

<h1 class="contentHeader">This is the header</h1>

使用 JSoup 的 traverse 方法,我遍历了 DOM 并找到了该元素及其属性,即:

doc.traverse(new NodeVisitor() {

            @Override
            public void head(Node node, int depth) {
                    System.out.println(node);
                    System.out.println("Node depth: " + depth);
                    Attributes attrList = node.attributes();
                    for (Attribute attr: attrList) {
                        System.out.println(attr);
                    }
....
}

这会产生:

<h1 class="contentHeader">This is the header</h1>
Node depth: 8
class="contentHeader"

我现在想做的是编写一个单行实现来查找这个元素。我一直在阅读 JSoup Cookbook似乎应该可以通过使用 eq 选择器来指定深度,但我没有运气。我能想到的最好的办法是:

System.out.println(doc.select("h1.contentHeader:eq(8)"));   

但是这没有输出任何数据。我要么错过了一些重要的东西,误解了 API,要么就是完全错误。

任何意见或建议将不胜感激。

最佳答案

eq 是CSS的伪类/选择器,它不用于按深度选择。这是关于 what eq does 的正确解释:

The index-related selectors (:eq(), :lt(), :gt(), :even, :odd) filter the set of elements that have matched the expressions that precede them. They narrow the set down based on the order of the elements within this matched set. For example, if elements are first selected with a class selector (.myclass) and four elements are returned, these elements are given indices 0 through 3 for the purposes of these selectors.

Note that since JavaScript arrays use 0-based indexing, these selectors reflect that fact. This is why $( ".myclass:eq(1)") selects the second element in the document with the class myclass, rather than the first. In contrast, :nth-child(n) uses 1-based indexing to conform to the CSS specification.

因此,eq 与深度无关。

但是,如果您的 HTML 有 class 属性,为什么不使用它:

System.out.println(doc.select("h1.contentHeader"));

你还可以写一个极其descendant selector对于这个节点(这只是一个例子,因为我不知道你的 HTML 结构):

System.out.println(doc.select("body div .someClass div div h1.contentHeader"));

关于java - Jsoup 选择深度元素(来自父级的 DOM 级别),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36813116/

相关文章:

java - 网页的 HTML 和 Jsoup 响应不一样

java - 如何使用 openjpa 将实体从一个数据库移动到另一个数据库?

java - java中的递归和if语句

java - 以简单的方式创建对象的副本

java - 使用 Jsoup 自动解析 CDATA 内标签的方法,无需替换

java - JSoup 从 <td> 标签中提取值

java - JSOUP 在 HTML 文件中找到所有具有 ALT 属性的图像?

java - 使用编程 TestNG 运行 Spring 上下文测试

java - 在jframe resizeize上调整cubiccurve的大小

java - Jsoup 无法从网页获取完整内容?