尝试使用 Jsoup 1.10.3
获取数据,eq
选择器似乎无法正常工作。
我尝试了第n个子项,但似乎它没有得到第二个表(表:第n个子项(2))。
我的选择器正确吗?
html > body > table:nth-child(2) > tbody > tr:nth-child(2) > td:nth-child(2)
在下面的示例中,尝试提取值 232323
最佳答案
您可能会遇到几个问题。首先,我认为您不想使用 :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 的每个层次结构级别。由于表始终包含 tbody
、 tr
和 td
元素,因此您可以执行以下操作:
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/