JSoup 获得第 child 个 div

JSoup get first child of div

我正在尝试使用 JSoup 解析如下所示的结构。

<div class="bigClass">
    <a href="foo.com"> Field 1</a>
    <a href="bar.com"> Field 2</a>
    <a href="baz.com"> Field 3</a>
</div>

现在,我正在使用以下代码获取 div class "bigClass"[= 的全部文本内容17=]

doc = Jsoup.connect("http://foobar.com").userAgent(userAgent).timeout(1000).get();
price = doc.getElementsByClass("bigClass");
System.out.println(price.text());

如何只得到第一个child("Field 1"),而不管<a>class和URL?

BeautifulSoup python 的类似问题:Beautiful soup getting the first child

我可能正在寻找

doc.getElementsByClass("bigClass").first().child(0)
  • getElementsByClass("bigClass") returns 所有元素 bigClass
  • 但我们想获得特定的(可能是第一个)
  • 在第一个元素上 select 它的第一个子节点(子节点从 0 开始索引)。

或者,您可以使用以下两个选项之一:

选项 1

doc.select("div.bigClass > a:first-of-type");

演示:http://try.jsoup.org/~btbp8Fb1xrPf38dTYbplLz5lA3Y

选项 2

doc.select("div.bigClass > a:first-child");

演示:http://try.jsoup.org/~mj8CAaWTtQEicyd75bSHDV3_KeA