java - Jsoup eq 选择器没有返回值

标签 java jsoup html-parsing

尝试使用 Jsoup 1.10.3 获取数据,eq 选择器似乎无法正常工作。

我尝试了第n个子项,但似乎它没有得到第二个表(表:第n个子项(2))。

我的选择器正确吗?

 html > body > table:nth-child(2) > tbody > tr:nth-child(2) > td:nth-child(2)

在下面的示例中,尝试提取值 232323

Here is the try it sample

最佳答案

您可能会遇到几个问题。首先,我认为您不想使用 :nth-child(an+b) 选择器。这是 jsoup docs 中对该选择器的解释:

:nth-child(an+b) elements that have an+b-1 siblings before it in the document tree, for any positive integer or zero value of n, and has a parent element. For values of a and b greater than zero, this effectively divides the element's children into groups of a elements (the last group taking the remainder), and selecting the bth element of each group. For example, this allows the selectors to address every other row in a table, and could be used to alternate the color of paragraph text in a cycle of four. The a and b values must be integers (positive, negative, or zero). The index of the first child of an element is 1.

我猜您想使用 :table:nth-of-type(n) 选择器。

第二,你只用选择器选择元素,但你想要获取可见内容232323,它只是你选择的元素的一个内部节点。所以缺少的是你获取内容的部分。有几种方法可以做到这一点。我再次建议您阅读文档。尤其是cookbook对初学者很有帮助。我想你可以使用这样的东西:

String content = element.text();

第三,使用 CSS 选择器,您确实需要遍历 DOM 的每个层次结构级别。由于表始终包含 tbodytrtd 元素,因此您可以执行以下操作:

String content = document.select("table:nth-of-type(2) tr:nth-of-type(2) td:last-of-type").text();

注意,我手头没有java编译器。请小心使用我的代码。

关于java - Jsoup eq 选择器没有返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45846108/

相关文章:

java - Jsoup 提取 div 的子元素

java - 获取文本节点内 anchor 中的文本

php - 简单的 html dom : how get a tag without certain attribute

Java 编译器不优化字符串连接

java - 从不同的集合中检索唯一的元素集合

java - Jsoup选择器: 2nd div after h2

php - 使用php从html页面中提取图像url

java - 如何迭代数组列表并根据条件添加或删除对象?

java - 访问修饰符和访问说明符有什么区别

html - 如何从shell脚本中的html表中提取数据?