这是一些原始的 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 indices0
through3
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 classmyclass
, 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/